home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / lib-tk / Tkinter.py < prev    next >
Text File  |  2009-11-02  |  159KB  |  3,778 lines

  1. """Wrapper functions for Tcl/Tk.
  2.  
  3. Tkinter provides classes which allow the display, positioning and
  4. control of widgets. Toplevel widgets are Tk and Toplevel. Other
  5. widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
  6. Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
  7. LabelFrame and PanedWindow.
  8.  
  9. Properties of the widgets are specified with keyword arguments.
  10. Keyword arguments have the same name as the corresponding resource
  11. under Tk.
  12.  
  13. Widgets are positioned with one of the geometry managers Place, Pack
  14. or Grid. These managers can be called with methods place, pack, grid
  15. available in every Widget.
  16.  
  17. Actions are bound to events by resources (e.g. keyword argument
  18. command) or with the method bind.
  19.  
  20. Example (Hello, World):
  21. import Tkinter
  22. from Tkconstants import *
  23. tk = Tkinter.Tk()
  24. frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
  25. frame.pack(fill=BOTH,expand=1)
  26. label = Tkinter.Label(frame, text="Hello, World")
  27. label.pack(fill=X, expand=1)
  28. button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
  29. button.pack(side=BOTTOM)
  30. tk.mainloop()
  31. """
  32.  
  33. __version__ = "$Revision: 73770 $"
  34.  
  35. import sys
  36. if sys.platform == "win32":
  37.     # Attempt to configure Tcl/Tk without requiring PATH
  38.     import FixTk
  39. try:
  40.     import _tkinter
  41. except ImportError, msg:
  42.     raise ImportError, str(msg) + ', please install the python-tk package'
  43. tkinter = _tkinter # b/w compat for export
  44. TclError = _tkinter.TclError
  45. from types import *
  46. from Tkconstants import *
  47.  
  48. wantobjects = 1
  49.  
  50. TkVersion = float(_tkinter.TK_VERSION)
  51. TclVersion = float(_tkinter.TCL_VERSION)
  52.  
  53. READABLE = _tkinter.READABLE
  54. WRITABLE = _tkinter.WRITABLE
  55. EXCEPTION = _tkinter.EXCEPTION
  56.  
  57. # These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
  58. try: _tkinter.createfilehandler
  59. except AttributeError: _tkinter.createfilehandler = None
  60. try: _tkinter.deletefilehandler
  61. except AttributeError: _tkinter.deletefilehandler = None
  62.  
  63.  
  64. def _flatten(tuple):
  65.     """Internal function."""
  66.     res = ()
  67.     for item in tuple:
  68.         if type(item) in (TupleType, ListType):
  69.             res = res + _flatten(item)
  70.         elif item is not None:
  71.             res = res + (item,)
  72.     return res
  73.  
  74. try: _flatten = _tkinter._flatten
  75. except AttributeError: pass
  76.  
  77. def _cnfmerge(cnfs):
  78.     """Internal function."""
  79.     if type(cnfs) is DictionaryType:
  80.         return cnfs
  81.     elif type(cnfs) in (NoneType, StringType):
  82.         return cnfs
  83.     else:
  84.         cnf = {}
  85.         for c in _flatten(cnfs):
  86.             try:
  87.                 cnf.update(c)
  88.             except (AttributeError, TypeError), msg:
  89.                 print "_cnfmerge: fallback due to:", msg
  90.                 for k, v in c.items():
  91.                     cnf[k] = v
  92.         return cnf
  93.  
  94. try: _cnfmerge = _tkinter._cnfmerge
  95. except AttributeError: pass
  96.  
  97. class Event:
  98.     """Container for the properties of an event.
  99.  
  100.     Instances of this type are generated if one of the following events occurs:
  101.  
  102.     KeyPress, KeyRelease - for keyboard events
  103.     ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
  104.     Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
  105.     Colormap, Gravity, Reparent, Property, Destroy, Activate,
  106.     Deactivate - for window events.
  107.  
  108.     If a callback function for one of these events is registered
  109.     using bind, bind_all, bind_class, or tag_bind, the callback is
  110.     called with an Event as first argument. It will have the
  111.     following attributes (in braces are the event types for which
  112.     the attribute is valid):
  113.  
  114.         serial - serial number of event
  115.     num - mouse button pressed (ButtonPress, ButtonRelease)
  116.     focus - whether the window has the focus (Enter, Leave)
  117.     height - height of the exposed window (Configure, Expose)
  118.     width - width of the exposed window (Configure, Expose)
  119.     keycode - keycode of the pressed key (KeyPress, KeyRelease)
  120.     state - state of the event as a number (ButtonPress, ButtonRelease,
  121.                             Enter, KeyPress, KeyRelease,
  122.                             Leave, Motion)
  123.     state - state as a string (Visibility)
  124.     time - when the event occurred
  125.     x - x-position of the mouse
  126.     y - y-position of the mouse
  127.     x_root - x-position of the mouse on the screen
  128.              (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  129.     y_root - y-position of the mouse on the screen
  130.              (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  131.     char - pressed character (KeyPress, KeyRelease)
  132.     send_event - see X/Windows documentation
  133.     keysym - keysym of the event as a string (KeyPress, KeyRelease)
  134.     keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
  135.     type - type of the event as a number
  136.     widget - widget in which the event occurred
  137.     delta - delta of wheel movement (MouseWheel)
  138.     """
  139.     pass
  140.  
  141. _support_default_root = 1
  142. _default_root = None
  143.  
  144. def NoDefaultRoot():
  145.     """Inhibit setting of default root window.
  146.  
  147.     Call this function to inhibit that the first instance of
  148.     Tk is used for windows without an explicit parent window.
  149.     """
  150.     global _support_default_root
  151.     _support_default_root = 0
  152.     global _default_root
  153.     _default_root = None
  154.     del _default_root
  155.  
  156. def _tkerror(err):
  157.     """Internal function."""
  158.     pass
  159.  
  160. def _exit(code='0'):
  161.     """Internal function. Calling it will throw the exception SystemExit."""
  162.     raise SystemExit, code
  163.  
  164. _varnum = 0
  165. class Variable:
  166.     """Class to define value holders for e.g. buttons.
  167.  
  168.     Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
  169.     that constrain the type of the value returned from get()."""
  170.     _default = ""
  171.     def __init__(self, master=None, value=None, name=None):
  172.         """Construct a variable
  173.  
  174.         MASTER can be given as master widget.
  175.         VALUE is an optional value (defaults to "")
  176.         NAME is an optional Tcl name (defaults to PY_VARnum).
  177.  
  178.         If NAME matches an existing variable and VALUE is omitted
  179.         then the existing value is retained.
  180.         """
  181.         global _varnum
  182.         if not master:
  183.             master = _default_root
  184.         self._master = master
  185.         self._tk = master.tk
  186.         if name:
  187.             self._name = name
  188.         else:
  189.             self._name = 'PY_VAR' + repr(_varnum)
  190.             _varnum += 1
  191.         if value is not None:
  192.             self.set(value)
  193.         elif not self._tk.call("info", "exists", self._name):
  194.             self.set(self._default)
  195.     def __del__(self):
  196.         """Unset the variable in Tcl."""
  197.         self._tk.globalunsetvar(self._name)
  198.     def __str__(self):
  199.         """Return the name of the variable in Tcl."""
  200.         return self._name
  201.     def set(self, value):
  202.         """Set the variable to VALUE."""
  203.         return self._tk.globalsetvar(self._name, value)
  204.     def get(self):
  205.         """Return value of variable."""
  206.         return self._tk.globalgetvar(self._name)
  207.     def trace_variable(self, mode, callback):
  208.         """Define a trace callback for the variable.
  209.  
  210.         MODE is one of "r", "w", "u" for read, write, undefine.
  211.         CALLBACK must be a function which is called when
  212.         the variable is read, written or undefined.
  213.  
  214.         Return the name of the callback.
  215.         """
  216.         cbname = self._master._register(callback)
  217.         self._tk.call("trace", "variable", self._name, mode, cbname)
  218.         return cbname
  219.     trace = trace_variable
  220.     def trace_vdelete(self, mode, cbname):
  221.         """Delete the trace callback for a variable.
  222.  
  223.         MODE is one of "r", "w", "u" for read, write, undefine.
  224.         CBNAME is the name of the callback returned from trace_variable or trace.
  225.         """
  226.         self._tk.call("trace", "vdelete", self._name, mode, cbname)
  227.         self._master.deletecommand(cbname)
  228.     def trace_vinfo(self):
  229.         """Return all trace callback information."""
  230.         return map(self._tk.split, self._tk.splitlist(
  231.             self._tk.call("trace", "vinfo", self._name)))
  232.     def __eq__(self, other):
  233.         """Comparison for equality (==).
  234.  
  235.         Note: if the Variable's master matters to behavior
  236.         also compare self._master == other._master
  237.         """
  238.         return self.__class__.__name__ == other.__class__.__name__ \
  239.             and self._name == other._name
  240.  
  241. class StringVar(Variable):
  242.     """Value holder for strings variables."""
  243.     _default = ""
  244.     def __init__(self, master=None, value=None, name=None):
  245.         """Construct a string variable.
  246.  
  247.         MASTER can be given as master widget.
  248.         VALUE is an optional value (defaults to "")
  249.         NAME is an optional Tcl name (defaults to PY_VARnum).
  250.  
  251.         If NAME matches an existing variable and VALUE is omitted
  252.         then the existing value is retained.
  253.         """
  254.         Variable.__init__(self, master, value, name)
  255.  
  256.     def get(self):
  257.         """Return value of variable as string."""
  258.         value = self._tk.globalgetvar(self._name)
  259.         if isinstance(value, basestring):
  260.             return value
  261.         return str(value)
  262.  
  263. class IntVar(Variable):
  264.     """Value holder for integer variables."""
  265.     _default = 0
  266.     def __init__(self, master=None, value=None, name=None):
  267.         """Construct an integer variable.
  268.  
  269.         MASTER can be given as master widget.
  270.         VALUE is an optional value (defaults to 0)
  271.         NAME is an optional Tcl name (defaults to PY_VARnum).
  272.  
  273.         If NAME matches an existing variable and VALUE is omitted
  274.         then the existing value is retained.
  275.         """
  276.         Variable.__init__(self, master, value, name)
  277.  
  278.     def set(self, value):
  279.         """Set the variable to value, converting booleans to integers."""
  280.         if isinstance(value, bool):
  281.             value = int(value)
  282.         return Variable.set(self, value)
  283.  
  284.     def get(self):
  285.         """Return the value of the variable as an integer."""
  286.         return getint(self._tk.globalgetvar(self._name))
  287.  
  288. class DoubleVar(Variable):
  289.     """Value holder for float variables."""
  290.     _default = 0.0
  291.     def __init__(self, master=None, value=None, name=None):
  292.         """Construct a float variable.
  293.  
  294.         MASTER can be given as master widget.
  295.         VALUE is an optional value (defaults to 0.0)
  296.         NAME is an optional Tcl name (defaults to PY_VARnum).
  297.  
  298.         If NAME matches an existing variable and VALUE is omitted
  299.         then the existing value is retained.
  300.         """
  301.         Variable.__init__(self, master, value, name)
  302.  
  303.     def get(self):
  304.         """Return the value of the variable as a float."""
  305.         return getdouble(self._tk.globalgetvar(self._name))
  306.  
  307. class BooleanVar(Variable):
  308.     """Value holder for boolean variables."""
  309.     _default = False
  310.     def __init__(self, master=None, value=None, name=None):
  311.         """Construct a boolean variable.
  312.  
  313.         MASTER can be given as master widget.
  314.         VALUE is an optional value (defaults to False)
  315.         NAME is an optional Tcl name (defaults to PY_VARnum).
  316.  
  317.         If NAME matches an existing variable and VALUE is omitted
  318.         then the existing value is retained.
  319.         """
  320.         Variable.__init__(self, master, value, name)
  321.  
  322.     def get(self):
  323.         """Return the value of the variable as a bool."""
  324.         return self._tk.getboolean(self._tk.globalgetvar(self._name))
  325.  
  326. def mainloop(n=0):
  327.     """Run the main loop of Tcl."""
  328.     _default_root.tk.mainloop(n)
  329.  
  330. getint = int
  331.  
  332. getdouble = float
  333.  
  334. def getboolean(s):
  335.     """Convert true and false to integer values 1 and 0."""
  336.     return _default_root.tk.getboolean(s)
  337.  
  338. # Methods defined on both toplevel and interior widgets
  339. class Misc:
  340.     """Internal class.
  341.  
  342.     Base class which defines methods common for interior widgets."""
  343.  
  344.     # XXX font command?
  345.     _tclCommands = None
  346.     def destroy(self):
  347.         """Internal function.
  348.  
  349.         Delete all Tcl commands created for
  350.         this widget in the Tcl interpreter."""
  351.         if self._tclCommands is not None:
  352.             for name in self._tclCommands:
  353.                 #print '- Tkinter: deleted command', name
  354.                 self.tk.deletecommand(name)
  355.             self._tclCommands = None
  356.     def deletecommand(self, name):
  357.         """Internal function.
  358.  
  359.         Delete the Tcl command provided in NAME."""
  360.         #print '- Tkinter: deleted command', name
  361.         self.tk.deletecommand(name)
  362.         try:
  363.             self._tclCommands.remove(name)
  364.         except ValueError:
  365.             pass
  366.     def tk_strictMotif(self, boolean=None):
  367.         """Set Tcl internal variable, whether the look and feel
  368.         should adhere to Motif.
  369.  
  370.         A parameter of 1 means adhere to Motif (e.g. no color
  371.         change if mouse passes over slider).
  372.         Returns the set value."""
  373.         return self.tk.getboolean(self.tk.call(
  374.             'set', 'tk_strictMotif', boolean))
  375.     def tk_bisque(self):
  376.         """Change the color scheme to light brown as used in Tk 3.6 and before."""
  377.         self.tk.call('tk_bisque')
  378.     def tk_setPalette(self, *args, **kw):
  379.         """Set a new color scheme for all widget elements.
  380.  
  381.         A single color as argument will cause that all colors of Tk
  382.         widget elements are derived from this.
  383.         Alternatively several keyword parameters and its associated
  384.         colors can be given. The following keywords are valid:
  385.         activeBackground, foreground, selectColor,
  386.         activeForeground, highlightBackground, selectBackground,
  387.         background, highlightColor, selectForeground,
  388.         disabledForeground, insertBackground, troughColor."""
  389.         self.tk.call(('tk_setPalette',)
  390.               + _flatten(args) + _flatten(kw.items()))
  391.     def tk_menuBar(self, *args):
  392.         """Do not use. Needed in Tk 3.6 and earlier."""
  393.         pass # obsolete since Tk 4.0
  394.     def wait_variable(self, name='PY_VAR'):
  395.         """Wait until the variable is modified.
  396.  
  397.         A parameter of type IntVar, StringVar, DoubleVar or
  398.         BooleanVar must be given."""
  399.         self.tk.call('tkwait', 'variable', name)
  400.     waitvar = wait_variable # XXX b/w compat
  401.     def wait_window(self, window=None):
  402.         """Wait until a WIDGET is destroyed.
  403.  
  404.         If no parameter is given self is used."""
  405.         if window is None:
  406.             window = self
  407.         self.tk.call('tkwait', 'window', window._w)
  408.     def wait_visibility(self, window=None):
  409.         """Wait until the visibility of a WIDGET changes
  410.         (e.g. it appears).
  411.  
  412.         If no parameter is given self is used."""
  413.         if window is None:
  414.             window = self
  415.         self.tk.call('tkwait', 'visibility', window._w)
  416.     def setvar(self, name='PY_VAR', value='1'):
  417.         """Set Tcl variable NAME to VALUE."""
  418.         self.tk.setvar(name, value)
  419.     def getvar(self, name='PY_VAR'):
  420.         """Return value of Tcl variable NAME."""
  421.         return self.tk.getvar(name)
  422.     getint = int
  423.     getdouble = float
  424.     def getboolean(self, s):
  425.         """Return a boolean value for Tcl boolean values true and false given as parameter."""
  426.         return self.tk.getboolean(s)
  427.     def focus_set(self):
  428.         """Direct input focus to this widget.
  429.  
  430.         If the application currently does not have the focus
  431.         this widget will get the focus if the application gets
  432.         the focus through the window manager."""
  433.         self.tk.call('focus', self._w)
  434.     focus = focus_set # XXX b/w compat?
  435.     def focus_force(self):
  436.         """Direct input focus to this widget even if the
  437.         application does not have the focus. Use with
  438.         caution!"""
  439.         self.tk.call('focus', '-force', self._w)
  440.     def focus_get(self):
  441.         """Return the widget which has currently the focus in the
  442.         application.
  443.  
  444.         Use focus_displayof to allow working with several
  445.         displays. Return None if application does not have
  446.         the focus."""
  447.         name = self.tk.call('focus')
  448.         if name == 'none' or not name: return None
  449.         return self._nametowidget(name)
  450.     def focus_displayof(self):
  451.         """Return the widget which has currently the focus on the
  452.         display where this widget is located.
  453.  
  454.         Return None if the application does not have the focus."""
  455.         name = self.tk.call('focus', '-displayof', self._w)
  456.         if name == 'none' or not name: return None
  457.         return self._nametowidget(name)
  458.     def focus_lastfor(self):
  459.         """Return the widget which would have the focus if top level
  460.         for this widget gets the focus from the window manager."""
  461.         name = self.tk.call('focus', '-lastfor', self._w)
  462.         if name == 'none' or not name: return None
  463.         return self._nametowidget(name)
  464.     def tk_focusFollowsMouse(self):
  465.         """The widget under mouse will get automatically focus. Can not
  466.         be disabled easily."""
  467.         self.tk.call('tk_focusFollowsMouse')
  468.     def tk_focusNext(self):
  469.         """Return the next widget in the focus order which follows
  470.         widget which has currently the focus.
  471.  
  472.         The focus order first goes to the next child, then to
  473.         the children of the child recursively and then to the
  474.         next sibling which is higher in the stacking order.  A
  475.         widget is omitted if it has the takefocus resource set
  476.         to 0."""
  477.         name = self.tk.call('tk_focusNext', self._w)
  478.         if not name: return None
  479.         return self._nametowidget(name)
  480.     def tk_focusPrev(self):
  481.         """Return previous widget in the focus order. See tk_focusNext for details."""
  482.         name = self.tk.call('tk_focusPrev', self._w)
  483.         if not name: return None
  484.         return self._nametowidget(name)
  485.     def after(self, ms, func=None, *args):
  486.         """Call function once after given time.
  487.  
  488.         MS specifies the time in milliseconds. FUNC gives the
  489.         function which shall be called. Additional parameters
  490.         are given as parameters to the function call.  Return
  491.         identifier to cancel scheduling with after_cancel."""
  492.         if not func:
  493.             # I'd rather use time.sleep(ms*0.001)
  494.             self.tk.call('after', ms)
  495.         else:
  496.             def callit():
  497.                 try:
  498.                     func(*args)
  499.                 finally:
  500.                     try:
  501.                         self.deletecommand(name)
  502.                     except TclError:
  503.                         pass
  504.             name = self._register(callit)
  505.             return self.tk.call('after', ms, name)
  506.     def after_idle(self, func, *args):
  507.         """Call FUNC once if the Tcl main loop has no event to
  508.         process.
  509.  
  510.         Return an identifier to cancel the scheduling with
  511.         after_cancel."""
  512.         return self.after('idle', func, *args)
  513.     def after_cancel(self, id):
  514.         """Cancel scheduling of function identified with ID.
  515.  
  516.         Identifier returned by after or after_idle must be
  517.         given as first parameter."""
  518.         try:
  519.             data = self.tk.call('after', 'info', id)
  520.             # In Tk 8.3, splitlist returns: (script, type)
  521.             # In Tk 8.4, splitlist may return (script, type) or (script,)
  522.             script = self.tk.splitlist(data)[0]
  523.             self.deletecommand(script)
  524.         except TclError:
  525.             pass
  526.         self.tk.call('after', 'cancel', id)
  527.     def bell(self, displayof=0):
  528.         """Ring a display's bell."""
  529.         self.tk.call(('bell',) + self._displayof(displayof))
  530.  
  531.     # Clipboard handling:
  532.     def clipboard_get(self, **kw):
  533.         """Retrieve data from the clipboard on window's display.
  534.  
  535.         The window keyword defaults to the root window of the Tkinter
  536.         application.
  537.  
  538.         The type keyword specifies the form in which the data is
  539.         to be returned and should be an atom name such as STRING
  540.         or FILE_NAME.  Type defaults to STRING.
  541.  
  542.         This command is equivalent to:
  543.  
  544.         selection_get(CLIPBOARD)
  545.         """
  546.         return self.tk.call(('clipboard', 'get') + self._options(kw))
  547.  
  548.     def clipboard_clear(self, **kw):
  549.         """Clear the data in the Tk clipboard.
  550.  
  551.         A widget specified for the optional displayof keyword
  552.         argument specifies the target display."""
  553.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  554.         self.tk.call(('clipboard', 'clear') + self._options(kw))
  555.     def clipboard_append(self, string, **kw):
  556.         """Append STRING to the Tk clipboard.
  557.  
  558.         A widget specified at the optional displayof keyword
  559.         argument specifies the target display. The clipboard
  560.         can be retrieved with selection_get."""
  561.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  562.         self.tk.call(('clipboard', 'append') + self._options(kw)
  563.               + ('--', string))
  564.     # XXX grab current w/o window argument
  565.     def grab_current(self):
  566.         """Return widget which has currently the grab in this application
  567.         or None."""
  568.         name = self.tk.call('grab', 'current', self._w)
  569.         if not name: return None
  570.         return self._nametowidget(name)
  571.     def grab_release(self):
  572.         """Release grab for this widget if currently set."""
  573.         self.tk.call('grab', 'release', self._w)
  574.     def grab_set(self):
  575.         """Set grab for this widget.
  576.  
  577.         A grab directs all events to this and descendant
  578.         widgets in the application."""
  579.         self.tk.call('grab', 'set', self._w)
  580.     def grab_set_global(self):
  581.         """Set global grab for this widget.
  582.  
  583.         A global grab directs all events to this and
  584.         descendant widgets on the display. Use with caution -
  585.         other applications do not get events anymore."""
  586.         self.tk.call('grab', 'set', '-global', self._w)
  587.     def grab_status(self):
  588.         """Return None, "local" or "global" if this widget has
  589.         no, a local or a global grab."""
  590.         status = self.tk.call('grab', 'status', self._w)
  591.         if status == 'none': status = None
  592.         return status
  593.     def option_add(self, pattern, value, priority = None):
  594.         """Set a VALUE (second parameter) for an option
  595.         PATTERN (first parameter).
  596.  
  597.         An optional third parameter gives the numeric priority
  598.         (defaults to 80)."""
  599.         self.tk.call('option', 'add', pattern, value, priority)
  600.     def option_clear(self):
  601.         """Clear the option database.
  602.  
  603.         It will be reloaded if option_add is called."""
  604.         self.tk.call('option', 'clear')
  605.     def option_get(self, name, className):
  606.         """Return the value for an option NAME for this widget
  607.         with CLASSNAME.
  608.  
  609.         Values with higher priority override lower values."""
  610.         return self.tk.call('option', 'get', self._w, name, className)
  611.     def option_readfile(self, fileName, priority = None):
  612.         """Read file FILENAME into the option database.
  613.  
  614.         An optional second parameter gives the numeric
  615.         priority."""
  616.         self.tk.call('option', 'readfile', fileName, priority)
  617.     def selection_clear(self, **kw):
  618.         """Clear the current X selection."""
  619.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  620.         self.tk.call(('selection', 'clear') + self._options(kw))
  621.     def selection_get(self, **kw):
  622.         """Return the contents of the current X selection.
  623.  
  624.         A keyword parameter selection specifies the name of
  625.         the selection and defaults to PRIMARY.  A keyword
  626.         parameter displayof specifies a widget on the display
  627.         to use."""
  628.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  629.         return self.tk.call(('selection', 'get') + self._options(kw))
  630.     def selection_handle(self, command, **kw):
  631.         """Specify a function COMMAND to call if the X
  632.         selection owned by this widget is queried by another
  633.         application.
  634.  
  635.         This function must return the contents of the
  636.         selection. The function will be called with the
  637.         arguments OFFSET and LENGTH which allows the chunking
  638.         of very long selections. The following keyword
  639.         parameters can be provided:
  640.         selection - name of the selection (default PRIMARY),
  641.         type - type of the selection (e.g. STRING, FILE_NAME)."""
  642.         name = self._register(command)
  643.         self.tk.call(('selection', 'handle') + self._options(kw)
  644.               + (self._w, name))
  645.     def selection_own(self, **kw):
  646.         """Become owner of X selection.
  647.  
  648.         A keyword parameter selection specifies the name of
  649.         the selection (default PRIMARY)."""
  650.         self.tk.call(('selection', 'own') +
  651.                  self._options(kw) + (self._w,))
  652.     def selection_own_get(self, **kw):
  653.         """Return owner of X selection.
  654.  
  655.         The following keyword parameter can
  656.         be provided:
  657.         selection - name of the selection (default PRIMARY),
  658.         type - type of the selection (e.g. STRING, FILE_NAME)."""
  659.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  660.         name = self.tk.call(('selection', 'own') + self._options(kw))
  661.         if not name: return None
  662.         return self._nametowidget(name)
  663.     def send(self, interp, cmd, *args):
  664.         """Send Tcl command CMD to different interpreter INTERP to be executed."""
  665.         return self.tk.call(('send', interp, cmd) + args)
  666.     def lower(self, belowThis=None):
  667.         """Lower this widget in the stacking order."""
  668.         self.tk.call('lower', self._w, belowThis)
  669.     def tkraise(self, aboveThis=None):
  670.         """Raise this widget in the stacking order."""
  671.         self.tk.call('raise', self._w, aboveThis)
  672.     lift = tkraise
  673.     def colormodel(self, value=None):
  674.         """Useless. Not implemented in Tk."""
  675.         return self.tk.call('tk', 'colormodel', self._w, value)
  676.     def winfo_atom(self, name, displayof=0):
  677.         """Return integer which represents atom NAME."""
  678.         args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
  679.         return getint(self.tk.call(args))
  680.     def winfo_atomname(self, id, displayof=0):
  681.         """Return name of atom with identifier ID."""
  682.         args = ('winfo', 'atomname') \
  683.                + self._displayof(displayof) + (id,)
  684.         return self.tk.call(args)
  685.     def winfo_cells(self):
  686.         """Return number of cells in the colormap for this widget."""
  687.         return getint(
  688.             self.tk.call('winfo', 'cells', self._w))
  689.     def winfo_children(self):
  690.         """Return a list of all widgets which are children of this widget."""
  691.         result = []
  692.         for child in self.tk.splitlist(
  693.             self.tk.call('winfo', 'children', self._w)):
  694.             try:
  695.                 # Tcl sometimes returns extra windows, e.g. for
  696.                 # menus; those need to be skipped
  697.                 result.append(self._nametowidget(child))
  698.             except KeyError:
  699.                 pass
  700.         return result
  701.  
  702.     def winfo_class(self):
  703.         """Return window class name of this widget."""
  704.         return self.tk.call('winfo', 'class', self._w)
  705.     def winfo_colormapfull(self):
  706.         """Return true if at the last color request the colormap was full."""
  707.         return self.tk.getboolean(
  708.             self.tk.call('winfo', 'colormapfull', self._w))
  709.     def winfo_containing(self, rootX, rootY, displayof=0):
  710.         """Return the widget which is at the root coordinates ROOTX, ROOTY."""
  711.         args = ('winfo', 'containing') \
  712.                + self._displayof(displayof) + (rootX, rootY)
  713.         name = self.tk.call(args)
  714.         if not name: return None
  715.         return self._nametowidget(name)
  716.     def winfo_depth(self):
  717.         """Return the number of bits per pixel."""
  718.         return getint(self.tk.call('winfo', 'depth', self._w))
  719.     def winfo_exists(self):
  720.         """Return true if this widget exists."""
  721.         return getint(
  722.             self.tk.call('winfo', 'exists', self._w))
  723.     def winfo_fpixels(self, number):
  724.         """Return the number of pixels for the given distance NUMBER
  725.         (e.g. "3c") as float."""
  726.         return getdouble(self.tk.call(
  727.             'winfo', 'fpixels', self._w, number))
  728.     def winfo_geometry(self):
  729.         """Return geometry string for this widget in the form "widthxheight+X+Y"."""
  730.         return self.tk.call('winfo', 'geometry', self._w)
  731.     def winfo_height(self):
  732.         """Return height of this widget."""
  733.         return getint(
  734.             self.tk.call('winfo', 'height', self._w))
  735.     def winfo_id(self):
  736.         """Return identifier ID for this widget."""
  737.         return self.tk.getint(
  738.             self.tk.call('winfo', 'id', self._w))
  739.     def winfo_interps(self, displayof=0):
  740.         """Return the name of all Tcl interpreters for this display."""
  741.         args = ('winfo', 'interps') + self._displayof(displayof)
  742.         return self.tk.splitlist(self.tk.call(args))
  743.     def winfo_ismapped(self):
  744.         """Return true if this widget is mapped."""
  745.         return getint(
  746.             self.tk.call('winfo', 'ismapped', self._w))
  747.     def winfo_manager(self):
  748.         """Return the window mananger name for this widget."""
  749.         return self.tk.call('winfo', 'manager', self._w)
  750.     def winfo_name(self):
  751.         """Return the name of this widget."""
  752.         return self.tk.call('winfo', 'name', self._w)
  753.     def winfo_parent(self):
  754.         """Return the name of the parent of this widget."""
  755.         return self.tk.call('winfo', 'parent', self._w)
  756.     def winfo_pathname(self, id, displayof=0):
  757.         """Return the pathname of the widget given by ID."""
  758.         args = ('winfo', 'pathname') \
  759.                + self._displayof(displayof) + (id,)
  760.         return self.tk.call(args)
  761.     def winfo_pixels(self, number):
  762.         """Rounded integer value of winfo_fpixels."""
  763.         return getint(
  764.             self.tk.call('winfo', 'pixels', self._w, number))
  765.     def winfo_pointerx(self):
  766.         """Return the x coordinate of the pointer on the root window."""
  767.         return getint(
  768.             self.tk.call('winfo', 'pointerx', self._w))
  769.     def winfo_pointerxy(self):
  770.         """Return a tuple of x and y coordinates of the pointer on the root window."""
  771.         return self._getints(
  772.             self.tk.call('winfo', 'pointerxy', self._w))
  773.     def winfo_pointery(self):
  774.         """Return the y coordinate of the pointer on the root window."""
  775.         return getint(
  776.             self.tk.call('winfo', 'pointery', self._w))
  777.     def winfo_reqheight(self):
  778.         """Return requested height of this widget."""
  779.         return getint(
  780.             self.tk.call('winfo', 'reqheight', self._w))
  781.     def winfo_reqwidth(self):
  782.         """Return requested width of this widget."""
  783.         return getint(
  784.             self.tk.call('winfo', 'reqwidth', self._w))
  785.     def winfo_rgb(self, color):
  786.         """Return tuple of decimal values for red, green, blue for
  787.         COLOR in this widget."""
  788.         return self._getints(
  789.             self.tk.call('winfo', 'rgb', self._w, color))
  790.     def winfo_rootx(self):
  791.         """Return x coordinate of upper left corner of this widget on the
  792.         root window."""
  793.         return getint(
  794.             self.tk.call('winfo', 'rootx', self._w))
  795.     def winfo_rooty(self):
  796.         """Return y coordinate of upper left corner of this widget on the
  797.         root window."""
  798.         return getint(
  799.             self.tk.call('winfo', 'rooty', self._w))
  800.     def winfo_screen(self):
  801.         """Return the screen name of this widget."""
  802.         return self.tk.call('winfo', 'screen', self._w)
  803.     def winfo_screencells(self):
  804.         """Return the number of the cells in the colormap of the screen
  805.         of this widget."""
  806.         return getint(
  807.             self.tk.call('winfo', 'screencells', self._w))
  808.     def winfo_screendepth(self):
  809.         """Return the number of bits per pixel of the root window of the
  810.         screen of this widget."""
  811.         return getint(
  812.             self.tk.call('winfo', 'screendepth', self._w))
  813.     def winfo_screenheight(self):
  814.         """Return the number of pixels of the height of the screen of this widget
  815.         in pixel."""
  816.         return getint(
  817.             self.tk.call('winfo', 'screenheight', self._w))
  818.     def winfo_screenmmheight(self):
  819.         """Return the number of pixels of the height of the screen of
  820.         this widget in mm."""
  821.         return getint(
  822.             self.tk.call('winfo', 'screenmmheight', self._w))
  823.     def winfo_screenmmwidth(self):
  824.         """Return the number of pixels of the width of the screen of
  825.         this widget in mm."""
  826.         return getint(
  827.             self.tk.call('winfo', 'screenmmwidth', self._w))
  828.     def winfo_screenvisual(self):
  829.         """Return one of the strings directcolor, grayscale, pseudocolor,
  830.         staticcolor, staticgray, or truecolor for the default
  831.         colormodel of this screen."""
  832.         return self.tk.call('winfo', 'screenvisual', self._w)
  833.     def winfo_screenwidth(self):
  834.         """Return the number of pixels of the width of the screen of
  835.         this widget in pixel."""
  836.         return getint(
  837.             self.tk.call('winfo', 'screenwidth', self._w))
  838.     def winfo_server(self):
  839.         """Return information of the X-Server of the screen of this widget in
  840.         the form "XmajorRminor vendor vendorVersion"."""
  841.         return self.tk.call('winfo', 'server', self._w)
  842.     def winfo_toplevel(self):
  843.         """Return the toplevel widget of this widget."""
  844.         return self._nametowidget(self.tk.call(
  845.             'winfo', 'toplevel', self._w))
  846.     def winfo_viewable(self):
  847.         """Return true if the widget and all its higher ancestors are mapped."""
  848.         return getint(
  849.             self.tk.call('winfo', 'viewable', self._w))
  850.     def winfo_visual(self):
  851.         """Return one of the strings directcolor, grayscale, pseudocolor,
  852.         staticcolor, staticgray, or truecolor for the
  853.         colormodel of this widget."""
  854.         return self.tk.call('winfo', 'visual', self._w)
  855.     def winfo_visualid(self):
  856.         """Return the X identifier for the visual for this widget."""
  857.         return self.tk.call('winfo', 'visualid', self._w)
  858.     def winfo_visualsavailable(self, includeids=0):
  859.         """Return a list of all visuals available for the screen
  860.         of this widget.
  861.  
  862.         Each item in the list consists of a visual name (see winfo_visual), a
  863.         depth and if INCLUDEIDS=1 is given also the X identifier."""
  864.         data = self.tk.split(
  865.             self.tk.call('winfo', 'visualsavailable', self._w,
  866.                      includeids and 'includeids' or None))
  867.         if type(data) is StringType:
  868.             data = [self.tk.split(data)]
  869.         return map(self.__winfo_parseitem, data)
  870.     def __winfo_parseitem(self, t):
  871.         """Internal function."""
  872.         return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
  873.     def __winfo_getint(self, x):
  874.         """Internal function."""
  875.         return int(x, 0)
  876.     def winfo_vrootheight(self):
  877.         """Return the height of the virtual root window associated with this
  878.         widget in pixels. If there is no virtual root window return the
  879.         height of the screen."""
  880.         return getint(
  881.             self.tk.call('winfo', 'vrootheight', self._w))
  882.     def winfo_vrootwidth(self):
  883.         """Return the width of the virtual root window associated with this
  884.         widget in pixel. If there is no virtual root window return the
  885.         width of the screen."""
  886.         return getint(
  887.             self.tk.call('winfo', 'vrootwidth', self._w))
  888.     def winfo_vrootx(self):
  889.         """Return the x offset of the virtual root relative to the root
  890.         window of the screen of this widget."""
  891.         return getint(
  892.             self.tk.call('winfo', 'vrootx', self._w))
  893.     def winfo_vrooty(self):
  894.         """Return the y offset of the virtual root relative to the root
  895.         window of the screen of this widget."""
  896.         return getint(
  897.             self.tk.call('winfo', 'vrooty', self._w))
  898.     def winfo_width(self):
  899.         """Return the width of this widget."""
  900.         return getint(
  901.             self.tk.call('winfo', 'width', self._w))
  902.     def winfo_x(self):
  903.         """Return the x coordinate of the upper left corner of this widget
  904.         in the parent."""
  905.         return getint(
  906.             self.tk.call('winfo', 'x', self._w))
  907.     def winfo_y(self):
  908.         """Return the y coordinate of the upper left corner of this widget
  909.         in the parent."""
  910.         return getint(
  911.             self.tk.call('winfo', 'y', self._w))
  912.     def update(self):
  913.         """Enter event loop until all pending events have been processed by Tcl."""
  914.         self.tk.call('update')
  915.     def update_idletasks(self):
  916.         """Enter event loop until all idle callbacks have been called. This
  917.         will update the display of windows but not process events caused by
  918.         the user."""
  919.         self.tk.call('update', 'idletasks')
  920.     def bindtags(self, tagList=None):
  921.         """Set or get the list of bindtags for this widget.
  922.  
  923.         With no argument return the list of all bindtags associated with
  924.         this widget. With a list of strings as argument the bindtags are
  925.         set to this list. The bindtags determine in which order events are
  926.         processed (see bind)."""
  927.         if tagList is None:
  928.             return self.tk.splitlist(
  929.                 self.tk.call('bindtags', self._w))
  930.         else:
  931.             self.tk.call('bindtags', self._w, tagList)
  932.     def _bind(self, what, sequence, func, add, needcleanup=1):
  933.         """Internal function."""
  934.         if type(func) is StringType:
  935.             self.tk.call(what + (sequence, func))
  936.         elif func:
  937.             funcid = self._register(func, self._substitute,
  938.                         needcleanup)
  939.             cmd = ('%sif {"[%s %s]" == "break"} break\n'
  940.                    %
  941.                    (add and '+' or '',
  942.                 funcid, self._subst_format_str))
  943.             self.tk.call(what + (sequence, cmd))
  944.             return funcid
  945.         elif sequence:
  946.             return self.tk.call(what + (sequence,))
  947.         else:
  948.             return self.tk.splitlist(self.tk.call(what))
  949.     def bind(self, sequence=None, func=None, add=None):
  950.         """Bind to this widget at event SEQUENCE a call to function FUNC.
  951.  
  952.         SEQUENCE is a string of concatenated event
  953.         patterns. An event pattern is of the form
  954.         <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
  955.         of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
  956.         Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
  957.         B3, Alt, Button4, B4, Double, Button5, B5 Triple,
  958.         Mod1, M1. TYPE is one of Activate, Enter, Map,
  959.         ButtonPress, Button, Expose, Motion, ButtonRelease
  960.         FocusIn, MouseWheel, Circulate, FocusOut, Property,
  961.         Colormap, Gravity Reparent, Configure, KeyPress, Key,
  962.         Unmap, Deactivate, KeyRelease Visibility, Destroy,
  963.         Leave and DETAIL is the button number for ButtonPress,
  964.         ButtonRelease and DETAIL is the Keysym for KeyPress and
  965.         KeyRelease. Examples are
  966.         <Control-Button-1> for pressing Control and mouse button 1 or
  967.         <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
  968.         An event pattern can also be a virtual event of the form
  969.         <<AString>> where AString can be arbitrary. This
  970.         event can be generated by event_generate.
  971.         If events are concatenated they must appear shortly
  972.         after each other.
  973.  
  974.         FUNC will be called if the event sequence occurs with an
  975.         instance of Event as argument. If the return value of FUNC is
  976.         "break" no further bound function is invoked.
  977.  
  978.         An additional boolean parameter ADD specifies whether FUNC will
  979.         be called additionally to the other bound function or whether
  980.         it will replace the previous function.
  981.  
  982.         Bind will return an identifier to allow deletion of the bound function with
  983.         unbind without memory leak.
  984.  
  985.         If FUNC or SEQUENCE is omitted the bound function or list
  986.         of bound events are returned."""
  987.  
  988.         return self._bind(('bind', self._w), sequence, func, add)
  989.     def unbind(self, sequence, funcid=None):
  990.         """Unbind for this widget for event SEQUENCE  the
  991.         function identified with FUNCID."""
  992.         self.tk.call('bind', self._w, sequence, '')
  993.         if funcid:
  994.             self.deletecommand(funcid)
  995.     def bind_all(self, sequence=None, func=None, add=None):
  996.         """Bind to all widgets at an event SEQUENCE a call to function FUNC.
  997.         An additional boolean parameter ADD specifies whether FUNC will
  998.         be called additionally to the other bound function or whether
  999.         it will replace the previous function. See bind for the return value."""
  1000.         return self._bind(('bind', 'all'), sequence, func, add, 0)
  1001.     def unbind_all(self, sequence):
  1002.         """Unbind for all widgets for event SEQUENCE all functions."""
  1003.         self.tk.call('bind', 'all' , sequence, '')
  1004.     def bind_class(self, className, sequence=None, func=None, add=None):
  1005.  
  1006.         """Bind to widgets with bindtag CLASSNAME at event
  1007.         SEQUENCE a call of function FUNC. An additional
  1008.         boolean parameter ADD specifies whether FUNC will be
  1009.         called additionally to the other bound function or
  1010.         whether it will replace the previous function. See bind for
  1011.         the return value."""
  1012.  
  1013.         return self._bind(('bind', className), sequence, func, add, 0)
  1014.     def unbind_class(self, className, sequence):
  1015.         """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
  1016.         all functions."""
  1017.         self.tk.call('bind', className , sequence, '')
  1018.     def mainloop(self, n=0):
  1019.         """Call the mainloop of Tk."""
  1020.         self.tk.mainloop(n)
  1021.     def quit(self):
  1022.         """Quit the Tcl interpreter. All widgets will be destroyed."""
  1023.         self.tk.quit()
  1024.     def _getints(self, string):
  1025.         """Internal function."""
  1026.         if string:
  1027.             return tuple(map(getint, self.tk.splitlist(string)))
  1028.     def _getdoubles(self, string):
  1029.         """Internal function."""
  1030.         if string:
  1031.             return tuple(map(getdouble, self.tk.splitlist(string)))
  1032.     def _getboolean(self, string):
  1033.         """Internal function."""
  1034.         if string:
  1035.             return self.tk.getboolean(string)
  1036.     def _displayof(self, displayof):
  1037.         """Internal function."""
  1038.         if displayof:
  1039.             return ('-displayof', displayof)
  1040.         if displayof is None:
  1041.             return ('-displayof', self._w)
  1042.         return ()
  1043.     def _options(self, cnf, kw = None):
  1044.         """Internal function."""
  1045.         if kw:
  1046.             cnf = _cnfmerge((cnf, kw))
  1047.         else:
  1048.             cnf = _cnfmerge(cnf)
  1049.         res = ()
  1050.         for k, v in cnf.items():
  1051.             if v is not None:
  1052.                 if k[-1] == '_': k = k[:-1]
  1053.                 if callable(v):
  1054.                     v = self._register(v)
  1055.                 elif isinstance(v, (tuple, list)):
  1056.                     nv = []
  1057.                     for item in v:
  1058.                         if not isinstance(item, (basestring, int)):
  1059.                             break
  1060.                         elif isinstance(item, int):
  1061.                             nv.append('%d' % item)
  1062.                         else:
  1063.                             # format it to proper Tcl code if it contains space
  1064.                             nv.append(('{%s}' if ' ' in item else '%s') % item)
  1065.                     else:
  1066.                         v = ' '.join(nv)
  1067.                 res = res + ('-'+k, v)
  1068.         return res
  1069.     def nametowidget(self, name):
  1070.         """Return the Tkinter instance of a widget identified by
  1071.         its Tcl name NAME."""
  1072.         name = str(name).split('.')
  1073.         w = self
  1074.  
  1075.         if not name[0]:
  1076.             w = w._root()
  1077.             name = name[1:]
  1078.  
  1079.         for n in name:
  1080.             if not n:
  1081.                 break
  1082.             w = w.children[n]
  1083.  
  1084.         return w
  1085.     _nametowidget = nametowidget
  1086.     def _register(self, func, subst=None, needcleanup=1):
  1087.         """Return a newly created Tcl function. If this
  1088.         function is called, the Python function FUNC will
  1089.         be executed. An optional function SUBST can
  1090.         be given which will be executed before FUNC."""
  1091.         f = CallWrapper(func, subst, self).__call__
  1092.         name = repr(id(f))
  1093.         try:
  1094.             func = func.im_func
  1095.         except AttributeError:
  1096.             pass
  1097.         try:
  1098.             name = name + func.__name__
  1099.         except AttributeError:
  1100.             pass
  1101.         self.tk.createcommand(name, f)
  1102.         if needcleanup:
  1103.             if self._tclCommands is None:
  1104.                 self._tclCommands = []
  1105.             self._tclCommands.append(name)
  1106.         return name
  1107.     register = _register
  1108.     def _root(self):
  1109.         """Internal function."""
  1110.         w = self
  1111.         while w.master: w = w.master
  1112.         return w
  1113.     _subst_format = ('%#', '%b', '%f', '%h', '%k',
  1114.              '%s', '%t', '%w', '%x', '%y',
  1115.              '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
  1116.     _subst_format_str = " ".join(_subst_format)
  1117.     def _substitute(self, *args):
  1118.         """Internal function."""
  1119.         if len(args) != len(self._subst_format): return args
  1120.         getboolean = self.tk.getboolean
  1121.  
  1122.         getint = int
  1123.         def getint_event(s):
  1124.             """Tk changed behavior in 8.4.2, returning "??" rather more often."""
  1125.             try:
  1126.                 return int(s)
  1127.             except ValueError:
  1128.                 return s
  1129.  
  1130.         nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
  1131.         # Missing: (a, c, d, m, o, v, B, R)
  1132.         e = Event()
  1133.         # serial field: valid vor all events
  1134.         # number of button: ButtonPress and ButtonRelease events only
  1135.         # height field: Configure, ConfigureRequest, Create,
  1136.         # ResizeRequest, and Expose events only
  1137.         # keycode field: KeyPress and KeyRelease events only
  1138.         # time field: "valid for events that contain a time field"
  1139.         # width field: Configure, ConfigureRequest, Create, ResizeRequest,
  1140.         # and Expose events only
  1141.         # x field: "valid for events that contain a x field"
  1142.         # y field: "valid for events that contain a y field"
  1143.         # keysym as decimal: KeyPress and KeyRelease events only
  1144.         # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
  1145.         # KeyRelease,and Motion events
  1146.         e.serial = getint(nsign)
  1147.         e.num = getint_event(b)
  1148.         try: e.focus = getboolean(f)
  1149.         except TclError: pass
  1150.         e.height = getint_event(h)
  1151.         e.keycode = getint_event(k)
  1152.         e.state = getint_event(s)
  1153.         e.time = getint_event(t)
  1154.         e.width = getint_event(w)
  1155.         e.x = getint_event(x)
  1156.         e.y = getint_event(y)
  1157.         e.char = A
  1158.         try: e.send_event = getboolean(E)
  1159.         except TclError: pass
  1160.         e.keysym = K
  1161.         e.keysym_num = getint_event(N)
  1162.         e.type = T
  1163.         try:
  1164.             e.widget = self._nametowidget(W)
  1165.         except KeyError:
  1166.             e.widget = W
  1167.         e.x_root = getint_event(X)
  1168.         e.y_root = getint_event(Y)
  1169.         try:
  1170.             e.delta = getint(D)
  1171.         except ValueError:
  1172.             e.delta = 0
  1173.         return (e,)
  1174.     def _report_exception(self):
  1175.         """Internal function."""
  1176.         import sys
  1177.         exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
  1178.         root = self._root()
  1179.         root.report_callback_exception(exc, val, tb)
  1180.     def _configure(self, cmd, cnf, kw):
  1181.         """Internal function."""
  1182.         if kw:
  1183.             cnf = _cnfmerge((cnf, kw))
  1184.         elif cnf:
  1185.             cnf = _cnfmerge(cnf)
  1186.         if cnf is None:
  1187.             cnf = {}
  1188.             for x in self.tk.split(
  1189.                     self.tk.call(_flatten((self._w, cmd)))):
  1190.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  1191.             return cnf
  1192.         if type(cnf) is StringType:
  1193.             x = self.tk.split(
  1194.                     self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
  1195.             return (x[0][1:],) + x[1:]
  1196.         self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
  1197.     # These used to be defined in Widget:
  1198.     def configure(self, cnf=None, **kw):
  1199.         """Configure resources of a widget.
  1200.  
  1201.         The values for resources are specified as keyword
  1202.         arguments. To get an overview about
  1203.         the allowed keyword arguments call the method keys.
  1204.         """
  1205.         return self._configure('configure', cnf, kw)
  1206.     config = configure
  1207.     def cget(self, key):
  1208.         """Return the resource value for a KEY given as string."""
  1209.         return self.tk.call(self._w, 'cget', '-' + key)
  1210.     __getitem__ = cget
  1211.     def __setitem__(self, key, value):
  1212.         self.configure({key: value})
  1213.     def __contains__(self, key):
  1214.         raise TypeError("Tkinter objects don't support 'in' tests.")
  1215.     def keys(self):
  1216.         """Return a list of all resource names of this widget."""
  1217.         return map(lambda x: x[0][1:],
  1218.                self.tk.split(self.tk.call(self._w, 'configure')))
  1219.     def __str__(self):
  1220.         """Return the window path name of this widget."""
  1221.         return self._w
  1222.     # Pack methods that apply to the master
  1223.     _noarg_ = ['_noarg_']
  1224.     def pack_propagate(self, flag=_noarg_):
  1225.         """Set or get the status for propagation of geometry information.
  1226.  
  1227.         A boolean argument specifies whether the geometry information
  1228.         of the slaves will determine the size of this widget. If no argument
  1229.         is given the current setting will be returned.
  1230.         """
  1231.         if flag is Misc._noarg_:
  1232.             return self._getboolean(self.tk.call(
  1233.                 'pack', 'propagate', self._w))
  1234.         else:
  1235.             self.tk.call('pack', 'propagate', self._w, flag)
  1236.     propagate = pack_propagate
  1237.     def pack_slaves(self):
  1238.         """Return a list of all slaves of this widget
  1239.         in its packing order."""
  1240.         return map(self._nametowidget,
  1241.                self.tk.splitlist(
  1242.                    self.tk.call('pack', 'slaves', self._w)))
  1243.     slaves = pack_slaves
  1244.     # Place method that applies to the master
  1245.     def place_slaves(self):
  1246.         """Return a list of all slaves of this widget
  1247.         in its packing order."""
  1248.         return map(self._nametowidget,
  1249.                self.tk.splitlist(
  1250.                    self.tk.call(
  1251.                        'place', 'slaves', self._w)))
  1252.     # Grid methods that apply to the master
  1253.     def grid_bbox(self, column=None, row=None, col2=None, row2=None):
  1254.         """Return a tuple of integer coordinates for the bounding
  1255.         box of this widget controlled by the geometry manager grid.
  1256.  
  1257.         If COLUMN, ROW is given the bounding box applies from
  1258.         the cell with row and column 0 to the specified
  1259.         cell. If COL2 and ROW2 are given the bounding box
  1260.         starts at that cell.
  1261.  
  1262.         The returned integers specify the offset of the upper left
  1263.         corner in the master widget and the width and height.
  1264.         """
  1265.         args = ('grid', 'bbox', self._w)
  1266.         if column is not None and row is not None:
  1267.             args = args + (column, row)
  1268.         if col2 is not None and row2 is not None:
  1269.             args = args + (col2, row2)
  1270.         return self._getints(self.tk.call(*args)) or None
  1271.  
  1272.     bbox = grid_bbox
  1273.     def _grid_configure(self, command, index, cnf, kw):
  1274.         """Internal function."""
  1275.         if type(cnf) is StringType and not kw:
  1276.             if cnf[-1:] == '_':
  1277.                 cnf = cnf[:-1]
  1278.             if cnf[:1] != '-':
  1279.                 cnf = '-'+cnf
  1280.             options = (cnf,)
  1281.         else:
  1282.             options = self._options(cnf, kw)
  1283.         if not options:
  1284.             res = self.tk.call('grid',
  1285.                        command, self._w, index)
  1286.             words = self.tk.splitlist(res)
  1287.             dict = {}
  1288.             for i in range(0, len(words), 2):
  1289.                 key = words[i][1:]
  1290.                 value = words[i+1]
  1291.                 if not value:
  1292.                     value = None
  1293.                 elif '.' in value:
  1294.                     value = getdouble(value)
  1295.                 else:
  1296.                     value = getint(value)
  1297.                 dict[key] = value
  1298.             return dict
  1299.         res = self.tk.call(
  1300.                   ('grid', command, self._w, index)
  1301.                   + options)
  1302.         if len(options) == 1:
  1303.             if not res: return None
  1304.             # In Tk 7.5, -width can be a float
  1305.             if '.' in res: return getdouble(res)
  1306.             return getint(res)
  1307.     def grid_columnconfigure(self, index, cnf={}, **kw):
  1308.         """Configure column INDEX of a grid.
  1309.  
  1310.         Valid resources are minsize (minimum size of the column),
  1311.         weight (how much does additional space propagate to this column)
  1312.         and pad (how much space to let additionally)."""
  1313.         return self._grid_configure('columnconfigure', index, cnf, kw)
  1314.     columnconfigure = grid_columnconfigure
  1315.     def grid_location(self, x, y):
  1316.         """Return a tuple of column and row which identify the cell
  1317.         at which the pixel at position X and Y inside the master
  1318.         widget is located."""
  1319.         return self._getints(
  1320.             self.tk.call(
  1321.                 'grid', 'location', self._w, x, y)) or None
  1322.     def grid_propagate(self, flag=_noarg_):
  1323.         """Set or get the status for propagation of geometry information.
  1324.  
  1325.         A boolean argument specifies whether the geometry information
  1326.         of the slaves will determine the size of this widget. If no argument
  1327.         is given, the current setting will be returned.
  1328.         """
  1329.         if flag is Misc._noarg_:
  1330.             return self._getboolean(self.tk.call(
  1331.                 'grid', 'propagate', self._w))
  1332.         else:
  1333.             self.tk.call('grid', 'propagate', self._w, flag)
  1334.     def grid_rowconfigure(self, index, cnf={}, **kw):
  1335.         """Configure row INDEX of a grid.
  1336.  
  1337.         Valid resources are minsize (minimum size of the row),
  1338.         weight (how much does additional space propagate to this row)
  1339.         and pad (how much space to let additionally)."""
  1340.         return self._grid_configure('rowconfigure', index, cnf, kw)
  1341.     rowconfigure = grid_rowconfigure
  1342.     def grid_size(self):
  1343.         """Return a tuple of the number of column and rows in the grid."""
  1344.         return self._getints(
  1345.             self.tk.call('grid', 'size', self._w)) or None
  1346.     size = grid_size
  1347.     def grid_slaves(self, row=None, column=None):
  1348.         """Return a list of all slaves of this widget
  1349.         in its packing order."""
  1350.         args = ()
  1351.         if row is not None:
  1352.             args = args + ('-row', row)
  1353.         if column is not None:
  1354.             args = args + ('-column', column)
  1355.         return map(self._nametowidget,
  1356.                self.tk.splitlist(self.tk.call(
  1357.                    ('grid', 'slaves', self._w) + args)))
  1358.  
  1359.     # Support for the "event" command, new in Tk 4.2.
  1360.     # By Case Roole.
  1361.  
  1362.     def event_add(self, virtual, *sequences):
  1363.         """Bind a virtual event VIRTUAL (of the form <<Name>>)
  1364.         to an event SEQUENCE such that the virtual event is triggered
  1365.         whenever SEQUENCE occurs."""
  1366.         args = ('event', 'add', virtual) + sequences
  1367.         self.tk.call(args)
  1368.  
  1369.     def event_delete(self, virtual, *sequences):
  1370.         """Unbind a virtual event VIRTUAL from SEQUENCE."""
  1371.         args = ('event', 'delete', virtual) + sequences
  1372.         self.tk.call(args)
  1373.  
  1374.     def event_generate(self, sequence, **kw):
  1375.         """Generate an event SEQUENCE. Additional
  1376.         keyword arguments specify parameter of the event
  1377.         (e.g. x, y, rootx, rooty)."""
  1378.         args = ('event', 'generate', self._w, sequence)
  1379.         for k, v in kw.items():
  1380.             args = args + ('-%s' % k, str(v))
  1381.         self.tk.call(args)
  1382.  
  1383.     def event_info(self, virtual=None):
  1384.         """Return a list of all virtual events or the information
  1385.         about the SEQUENCE bound to the virtual event VIRTUAL."""
  1386.         return self.tk.splitlist(
  1387.             self.tk.call('event', 'info', virtual))
  1388.  
  1389.     # Image related commands
  1390.  
  1391.     def image_names(self):
  1392.         """Return a list of all existing image names."""
  1393.         return self.tk.call('image', 'names')
  1394.  
  1395.     def image_types(self):
  1396.         """Return a list of all available image types (e.g. phote bitmap)."""
  1397.         return self.tk.call('image', 'types')
  1398.  
  1399.  
  1400. class CallWrapper:
  1401.     """Internal class. Stores function to call when some user
  1402.     defined Tcl function is called e.g. after an event occurred."""
  1403.     def __init__(self, func, subst, widget):
  1404.         """Store FUNC, SUBST and WIDGET as members."""
  1405.         self.func = func
  1406.         self.subst = subst
  1407.         self.widget = widget
  1408.     def __call__(self, *args):
  1409.         """Apply first function SUBST to arguments, than FUNC."""
  1410.         try:
  1411.             if self.subst:
  1412.                 args = self.subst(*args)
  1413.             return self.func(*args)
  1414.         except SystemExit, msg:
  1415.             raise SystemExit, msg
  1416.         except:
  1417.             self.widget._report_exception()
  1418.  
  1419.  
  1420. class Wm:
  1421.     """Provides functions for the communication with the window manager."""
  1422.  
  1423.     def wm_aspect(self,
  1424.               minNumer=None, minDenom=None,
  1425.               maxNumer=None, maxDenom=None):
  1426.         """Instruct the window manager to set the aspect ratio (width/height)
  1427.         of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
  1428.         of the actual values if no argument is given."""
  1429.         return self._getints(
  1430.             self.tk.call('wm', 'aspect', self._w,
  1431.                      minNumer, minDenom,
  1432.                      maxNumer, maxDenom))
  1433.     aspect = wm_aspect
  1434.  
  1435.     def wm_attributes(self, *args):
  1436.         """This subcommand returns or sets platform specific attributes
  1437.  
  1438.         The first form returns a list of the platform specific flags and
  1439.         their values. The second form returns the value for the specific
  1440.         option. The third form sets one or more of the values. The values
  1441.         are as follows:
  1442.  
  1443.         On Windows, -disabled gets or sets whether the window is in a
  1444.         disabled state. -toolwindow gets or sets the style of the window
  1445.         to toolwindow (as defined in the MSDN). -topmost gets or sets
  1446.         whether this is a topmost window (displays above all other
  1447.         windows).
  1448.  
  1449.         On Macintosh, XXXXX
  1450.  
  1451.         On Unix, there are currently no special attribute values.
  1452.         """
  1453.         args = ('wm', 'attributes', self._w) + args
  1454.         return self.tk.call(args)
  1455.     attributes=wm_attributes
  1456.  
  1457.     def wm_client(self, name=None):
  1458.         """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
  1459.         current value."""
  1460.         return self.tk.call('wm', 'client', self._w, name)
  1461.     client = wm_client
  1462.     def wm_colormapwindows(self, *wlist):
  1463.         """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
  1464.         of this widget. This list contains windows whose colormaps differ from their
  1465.         parents. Return current list of widgets if WLIST is empty."""
  1466.         if len(wlist) > 1:
  1467.             wlist = (wlist,) # Tk needs a list of windows here
  1468.         args = ('wm', 'colormapwindows', self._w) + wlist
  1469.         return map(self._nametowidget, self.tk.call(args))
  1470.     colormapwindows = wm_colormapwindows
  1471.     def wm_command(self, value=None):
  1472.         """Store VALUE in WM_COMMAND property. It is the command
  1473.         which shall be used to invoke the application. Return current
  1474.         command if VALUE is None."""
  1475.         return self.tk.call('wm', 'command', self._w, value)
  1476.     command = wm_command
  1477.     def wm_deiconify(self):
  1478.         """Deiconify this widget. If it was never mapped it will not be mapped.
  1479.         On Windows it will raise this widget and give it the focus."""
  1480.         return self.tk.call('wm', 'deiconify', self._w)
  1481.     deiconify = wm_deiconify
  1482.     def wm_focusmodel(self, model=None):
  1483.         """Set focus model to MODEL. "active" means that this widget will claim
  1484.         the focus itself, "passive" means that the window manager shall give
  1485.         the focus. Return current focus model if MODEL is None."""
  1486.         return self.tk.call('wm', 'focusmodel', self._w, model)
  1487.     focusmodel = wm_focusmodel
  1488.     def wm_frame(self):
  1489.         """Return identifier for decorative frame of this widget if present."""
  1490.         return self.tk.call('wm', 'frame', self._w)
  1491.     frame = wm_frame
  1492.     def wm_geometry(self, newGeometry=None):
  1493.         """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
  1494.         current value if None is given."""
  1495.         return self.tk.call('wm', 'geometry', self._w, newGeometry)
  1496.     geometry = wm_geometry
  1497.     def wm_grid(self,
  1498.          baseWidth=None, baseHeight=None,
  1499.          widthInc=None, heightInc=None):
  1500.         """Instruct the window manager that this widget shall only be
  1501.         resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
  1502.         height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
  1503.         number of grid units requested in Tk_GeometryRequest."""
  1504.         return self._getints(self.tk.call(
  1505.             'wm', 'grid', self._w,
  1506.             baseWidth, baseHeight, widthInc, heightInc))
  1507.     grid = wm_grid
  1508.     def wm_group(self, pathName=None):
  1509.         """Set the group leader widgets for related widgets to PATHNAME. Return
  1510.         the group leader of this widget if None is given."""
  1511.         return self.tk.call('wm', 'group', self._w, pathName)
  1512.     group = wm_group
  1513.     def wm_iconbitmap(self, bitmap=None, default=None):
  1514.         """Set bitmap for the iconified widget to BITMAP. Return
  1515.         the bitmap if None is given.
  1516.  
  1517.         Under Windows, the DEFAULT parameter can be used to set the icon
  1518.         for the widget and any descendents that don't have an icon set
  1519.         explicitly.  DEFAULT can be the relative path to a .ico file
  1520.         (example: root.iconbitmap(default='myicon.ico') ).  See Tk
  1521.         documentation for more information."""
  1522.         if default:
  1523.             return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
  1524.         else:
  1525.             return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
  1526.     iconbitmap = wm_iconbitmap
  1527.     def wm_iconify(self):
  1528.         """Display widget as icon."""
  1529.         return self.tk.call('wm', 'iconify', self._w)
  1530.     iconify = wm_iconify
  1531.     def wm_iconmask(self, bitmap=None):
  1532.         """Set mask for the icon bitmap of this widget. Return the
  1533.         mask if None is given."""
  1534.         return self.tk.call('wm', 'iconmask', self._w, bitmap)
  1535.     iconmask = wm_iconmask
  1536.     def wm_iconname(self, newName=None):
  1537.         """Set the name of the icon for this widget. Return the name if
  1538.         None is given."""
  1539.         return self.tk.call('wm', 'iconname', self._w, newName)
  1540.     iconname = wm_iconname
  1541.     def wm_iconposition(self, x=None, y=None):
  1542.         """Set the position of the icon of this widget to X and Y. Return
  1543.         a tuple of the current values of X and X if None is given."""
  1544.         return self._getints(self.tk.call(
  1545.             'wm', 'iconposition', self._w, x, y))
  1546.     iconposition = wm_iconposition
  1547.     def wm_iconwindow(self, pathName=None):
  1548.         """Set widget PATHNAME to be displayed instead of icon. Return the current
  1549.         value if None is given."""
  1550.         return self.tk.call('wm', 'iconwindow', self._w, pathName)
  1551.     iconwindow = wm_iconwindow
  1552.     def wm_maxsize(self, width=None, height=None):
  1553.         """Set max WIDTH and HEIGHT for this widget. If the window is gridded
  1554.         the values are given in grid units. Return the current values if None
  1555.         is given."""
  1556.         return self._getints(self.tk.call(
  1557.             'wm', 'maxsize', self._w, width, height))
  1558.     maxsize = wm_maxsize
  1559.     def wm_minsize(self, width=None, height=None):
  1560.         """Set min WIDTH and HEIGHT for this widget. If the window is gridded
  1561.         the values are given in grid units. Return the current values if None
  1562.         is given."""
  1563.         return self._getints(self.tk.call(
  1564.             'wm', 'minsize', self._w, width, height))
  1565.     minsize = wm_minsize
  1566.     def wm_overrideredirect(self, boolean=None):
  1567.         """Instruct the window manager to ignore this widget
  1568.         if BOOLEAN is given with 1. Return the current value if None
  1569.         is given."""
  1570.         return self._getboolean(self.tk.call(
  1571.             'wm', 'overrideredirect', self._w, boolean))
  1572.     overrideredirect = wm_overrideredirect
  1573.     def wm_positionfrom(self, who=None):
  1574.         """Instruct the window manager that the position of this widget shall
  1575.         be defined by the user if WHO is "user", and by its own policy if WHO is
  1576.         "program"."""
  1577.         return self.tk.call('wm', 'positionfrom', self._w, who)
  1578.     positionfrom = wm_positionfrom
  1579.     def wm_protocol(self, name=None, func=None):
  1580.         """Bind function FUNC to command NAME for this widget.
  1581.         Return the function bound to NAME if None is given. NAME could be
  1582.         e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
  1583.         if hasattr(func, '__call__'):
  1584.             command = self._register(func)
  1585.         else:
  1586.             command = func
  1587.         return self.tk.call(
  1588.             'wm', 'protocol', self._w, name, command)
  1589.     protocol = wm_protocol
  1590.     def wm_resizable(self, width=None, height=None):
  1591.         """Instruct the window manager whether this width can be resized
  1592.         in WIDTH or HEIGHT. Both values are boolean values."""
  1593.         return self.tk.call('wm', 'resizable', self._w, width, height)
  1594.     resizable = wm_resizable
  1595.     def wm_sizefrom(self, who=None):
  1596.         """Instruct the window manager that the size of this widget shall
  1597.         be defined by the user if WHO is "user", and by its own policy if WHO is
  1598.         "program"."""
  1599.         return self.tk.call('wm', 'sizefrom', self._w, who)
  1600.     sizefrom = wm_sizefrom
  1601.     def wm_state(self, newstate=None):
  1602.         """Query or set the state of this widget as one of normal, icon,
  1603.         iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
  1604.         return self.tk.call('wm', 'state', self._w, newstate)
  1605.     state = wm_state
  1606.     def wm_title(self, string=None):
  1607.         """Set the title of this widget."""
  1608.         return self.tk.call('wm', 'title', self._w, string)
  1609.     title = wm_title
  1610.     def wm_transient(self, master=None):
  1611.         """Instruct the window manager that this widget is transient
  1612.         with regard to widget MASTER."""
  1613.         return self.tk.call('wm', 'transient', self._w, master)
  1614.     transient = wm_transient
  1615.     def wm_withdraw(self):
  1616.         """Withdraw this widget from the screen such that it is unmapped
  1617.         and forgotten by the window manager. Re-draw it with wm_deiconify."""
  1618.         return self.tk.call('wm', 'withdraw', self._w)
  1619.     withdraw = wm_withdraw
  1620.  
  1621.  
  1622. class Tk(Misc, Wm):
  1623.     """Toplevel widget of Tk which represents mostly the main window
  1624.     of an appliation. It has an associated Tcl interpreter."""
  1625.     _w = '.'
  1626.     def __init__(self, screenName=None, baseName=None, className='Tk',
  1627.                  useTk=1, sync=0, use=None):
  1628.         """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
  1629.         be created. BASENAME will be used for the identification of the profile file (see
  1630.         readprofile).
  1631.         It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
  1632.         is the name of the widget class."""
  1633.         self.master = None
  1634.         self.children = {}
  1635.         self._tkloaded = 0
  1636.         # to avoid recursions in the getattr code in case of failure, we
  1637.         # ensure that self.tk is always _something_.
  1638.         self.tk = None
  1639.         if baseName is None:
  1640.             import sys, os
  1641.             baseName = os.path.basename(sys.argv[0])
  1642.             baseName, ext = os.path.splitext(baseName)
  1643.             if ext not in ('.py', '.pyc', '.pyo'):
  1644.                 baseName = baseName + ext
  1645.         interactive = 0
  1646.         self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
  1647.         if useTk:
  1648.             self._loadtk()
  1649.         self.readprofile(baseName, className)
  1650.     def loadtk(self):
  1651.         if not self._tkloaded:
  1652.             self.tk.loadtk()
  1653.             self._loadtk()
  1654.     def _loadtk(self):
  1655.         self._tkloaded = 1
  1656.         global _default_root
  1657.         # Version sanity checks
  1658.         tk_version = self.tk.getvar('tk_version')
  1659.         if tk_version != _tkinter.TK_VERSION:
  1660.             raise RuntimeError, \
  1661.             "tk.h version (%s) doesn't match libtk.a version (%s)" \
  1662.             % (_tkinter.TK_VERSION, tk_version)
  1663.         # Under unknown circumstances, tcl_version gets coerced to float
  1664.         tcl_version = str(self.tk.getvar('tcl_version'))
  1665.         if tcl_version != _tkinter.TCL_VERSION:
  1666.             raise RuntimeError, \
  1667.             "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
  1668.             % (_tkinter.TCL_VERSION, tcl_version)
  1669.         if TkVersion < 4.0:
  1670.             raise RuntimeError, \
  1671.             "Tk 4.0 or higher is required; found Tk %s" \
  1672.             % str(TkVersion)
  1673.         # Create and register the tkerror and exit commands
  1674.         # We need to inline parts of _register here, _ register
  1675.         # would register differently-named commands.
  1676.         if self._tclCommands is None:
  1677.             self._tclCommands = []
  1678.         self.tk.createcommand('tkerror', _tkerror)
  1679.         self.tk.createcommand('exit', _exit)
  1680.         self._tclCommands.append('tkerror')
  1681.         self._tclCommands.append('exit')
  1682.         if _support_default_root and not _default_root:
  1683.             _default_root = self
  1684.         self.protocol("WM_DELETE_WINDOW", self.destroy)
  1685.     def destroy(self):
  1686.         """Destroy this and all descendants widgets. This will
  1687.         end the application of this Tcl interpreter."""
  1688.         for c in self.children.values(): c.destroy()
  1689.         self.tk.call('destroy', self._w)
  1690.         Misc.destroy(self)
  1691.         global _default_root
  1692.         if _support_default_root and _default_root is self:
  1693.             _default_root = None
  1694.     def readprofile(self, baseName, className):
  1695.         """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
  1696.         the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
  1697.         such a file exists in the home directory."""
  1698.         import os
  1699.         if os.environ.has_key('HOME'): home = os.environ['HOME']
  1700.         else: home = os.curdir
  1701.         class_tcl = os.path.join(home, '.%s.tcl' % className)
  1702.         class_py = os.path.join(home, '.%s.py' % className)
  1703.         base_tcl = os.path.join(home, '.%s.tcl' % baseName)
  1704.         base_py = os.path.join(home, '.%s.py' % baseName)
  1705.         dir = {'self': self}
  1706.         exec 'from Tkinter import *' in dir
  1707.         if os.path.isfile(class_tcl):
  1708.             self.tk.call('source', class_tcl)
  1709.         if os.path.isfile(class_py):
  1710.             execfile(class_py, dir)
  1711.         if os.path.isfile(base_tcl):
  1712.             self.tk.call('source', base_tcl)
  1713.         if os.path.isfile(base_py):
  1714.             execfile(base_py, dir)
  1715.     def report_callback_exception(self, exc, val, tb):
  1716.         """Internal function. It reports exception on sys.stderr."""
  1717.         import traceback, sys
  1718.         sys.stderr.write("Exception in Tkinter callback\n")
  1719.         sys.last_type = exc
  1720.         sys.last_value = val
  1721.         sys.last_traceback = tb
  1722.         traceback.print_exception(exc, val, tb)
  1723.     def __getattr__(self, attr):
  1724.         "Delegate attribute access to the interpreter object"
  1725.         return getattr(self.tk, attr)
  1726.  
  1727. # Ideally, the classes Pack, Place and Grid disappear, the
  1728. # pack/place/grid methods are defined on the Widget class, and
  1729. # everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
  1730. # ...), with pack(), place() and grid() being short for
  1731. # pack_configure(), place_configure() and grid_columnconfigure(), and
  1732. # forget() being short for pack_forget().  As a practical matter, I'm
  1733. # afraid that there is too much code out there that may be using the
  1734. # Pack, Place or Grid class, so I leave them intact -- but only as
  1735. # backwards compatibility features.  Also note that those methods that
  1736. # take a master as argument (e.g. pack_propagate) have been moved to
  1737. # the Misc class (which now incorporates all methods common between
  1738. # toplevel and interior widgets).  Again, for compatibility, these are
  1739. # copied into the Pack, Place or Grid class.
  1740.  
  1741.  
  1742. def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
  1743.     return Tk(screenName, baseName, className, useTk)
  1744.  
  1745. class Pack:
  1746.     """Geometry manager Pack.
  1747.  
  1748.     Base class to use the methods pack_* in every widget."""
  1749.     def pack_configure(self, cnf={}, **kw):
  1750.         """Pack a widget in the parent widget. Use as options:
  1751.         after=widget - pack it after you have packed widget
  1752.         anchor=NSEW (or subset) - position widget according to
  1753.                                   given direction
  1754.         before=widget - pack it before you will pack widget
  1755.         expand=bool - expand widget if parent size grows
  1756.         fill=NONE or X or Y or BOTH - fill widget if widget grows
  1757.         in=master - use master to contain this widget
  1758.         in_=master - see 'in' option description
  1759.         ipadx=amount - add internal padding in x direction
  1760.         ipady=amount - add internal padding in y direction
  1761.         padx=amount - add padding in x direction
  1762.         pady=amount - add padding in y direction
  1763.         side=TOP or BOTTOM or LEFT or RIGHT -  where to add this widget.
  1764.         """
  1765.         self.tk.call(
  1766.               ('pack', 'configure', self._w)
  1767.               + self._options(cnf, kw))
  1768.     pack = configure = config = pack_configure
  1769.     def pack_forget(self):
  1770.         """Unmap this widget and do not use it for the packing order."""
  1771.         self.tk.call('pack', 'forget', self._w)
  1772.     forget = pack_forget
  1773.     def pack_info(self):
  1774.         """Return information about the packing options
  1775.         for this widget."""
  1776.         words = self.tk.splitlist(
  1777.             self.tk.call('pack', 'info', self._w))
  1778.         dict = {}
  1779.         for i in range(0, len(words), 2):
  1780.             key = words[i][1:]
  1781.             value = words[i+1]
  1782.             if value[:1] == '.':
  1783.                 value = self._nametowidget(value)
  1784.             dict[key] = value
  1785.         return dict
  1786.     info = pack_info
  1787.     propagate = pack_propagate = Misc.pack_propagate
  1788.     slaves = pack_slaves = Misc.pack_slaves
  1789.  
  1790. class Place:
  1791.     """Geometry manager Place.
  1792.  
  1793.     Base class to use the methods place_* in every widget."""
  1794.     def place_configure(self, cnf={}, **kw):
  1795.         """Place a widget in the parent widget. Use as options:
  1796.         in=master - master relative to which the widget is placed
  1797.         in_=master - see 'in' option description
  1798.         x=amount - locate anchor of this widget at position x of master
  1799.         y=amount - locate anchor of this widget at position y of master
  1800.         relx=amount - locate anchor of this widget between 0.0 and 1.0
  1801.                       relative to width of master (1.0 is right edge)
  1802.         rely=amount - locate anchor of this widget between 0.0 and 1.0
  1803.                       relative to height of master (1.0 is bottom edge)
  1804.         anchor=NSEW (or subset) - position anchor according to given direction
  1805.         width=amount - width of this widget in pixel
  1806.         height=amount - height of this widget in pixel
  1807.         relwidth=amount - width of this widget between 0.0 and 1.0
  1808.                           relative to width of master (1.0 is the same width
  1809.                           as the master)
  1810.         relheight=amount - height of this widget between 0.0 and 1.0
  1811.                            relative to height of master (1.0 is the same
  1812.                            height as the master)
  1813.         bordermode="inside" or "outside" - whether to take border width of
  1814.                                            master widget into account
  1815.         """
  1816.         self.tk.call(
  1817.               ('place', 'configure', self._w)
  1818.               + self._options(cnf, kw))
  1819.     place = configure = config = place_configure
  1820.     def place_forget(self):
  1821.         """Unmap this widget."""
  1822.         self.tk.call('place', 'forget', self._w)
  1823.     forget = place_forget
  1824.     def place_info(self):
  1825.         """Return information about the placing options
  1826.         for this widget."""
  1827.         words = self.tk.splitlist(
  1828.             self.tk.call('place', 'info', self._w))
  1829.         dict = {}
  1830.         for i in range(0, len(words), 2):
  1831.             key = words[i][1:]
  1832.             value = words[i+1]
  1833.             if value[:1] == '.':
  1834.                 value = self._nametowidget(value)
  1835.             dict[key] = value
  1836.         return dict
  1837.     info = place_info
  1838.     slaves = place_slaves = Misc.place_slaves
  1839.  
  1840. class Grid:
  1841.     """Geometry manager Grid.
  1842.  
  1843.     Base class to use the methods grid_* in every widget."""
  1844.     # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
  1845.     def grid_configure(self, cnf={}, **kw):
  1846.         """Position a widget in the parent widget in a grid. Use as options:
  1847.         column=number - use cell identified with given column (starting with 0)
  1848.         columnspan=number - this widget will span several columns
  1849.         in=master - use master to contain this widget
  1850.         in_=master - see 'in' option description
  1851.         ipadx=amount - add internal padding in x direction
  1852.         ipady=amount - add internal padding in y direction
  1853.         padx=amount - add padding in x direction
  1854.         pady=amount - add padding in y direction
  1855.         row=number - use cell identified with given row (starting with 0)
  1856.         rowspan=number - this widget will span several rows
  1857.         sticky=NSEW - if cell is larger on which sides will this
  1858.                       widget stick to the cell boundary
  1859.         """
  1860.         self.tk.call(
  1861.               ('grid', 'configure', self._w)
  1862.               + self._options(cnf, kw))
  1863.     grid = configure = config = grid_configure
  1864.     bbox = grid_bbox = Misc.grid_bbox
  1865.     columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
  1866.     def grid_forget(self):
  1867.         """Unmap this widget."""
  1868.         self.tk.call('grid', 'forget', self._w)
  1869.     forget = grid_forget
  1870.     def grid_remove(self):
  1871.         """Unmap this widget but remember the grid options."""
  1872.         self.tk.call('grid', 'remove', self._w)
  1873.     def grid_info(self):
  1874.         """Return information about the options
  1875.         for positioning this widget in a grid."""
  1876.         words = self.tk.splitlist(
  1877.             self.tk.call('grid', 'info', self._w))
  1878.         dict = {}
  1879.         for i in range(0, len(words), 2):
  1880.             key = words[i][1:]
  1881.             value = words[i+1]
  1882.             if value[:1] == '.':
  1883.                 value = self._nametowidget(value)
  1884.             dict[key] = value
  1885.         return dict
  1886.     info = grid_info
  1887.     location = grid_location = Misc.grid_location
  1888.     propagate = grid_propagate = Misc.grid_propagate
  1889.     rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
  1890.     size = grid_size = Misc.grid_size
  1891.     slaves = grid_slaves = Misc.grid_slaves
  1892.  
  1893. class BaseWidget(Misc):
  1894.     """Internal class."""
  1895.     def _setup(self, master, cnf):
  1896.         """Internal function. Sets up information about children."""
  1897.         if _support_default_root:
  1898.             global _default_root
  1899.             if not master:
  1900.                 if not _default_root:
  1901.                     _default_root = Tk()
  1902.                 master = _default_root
  1903.         self.master = master
  1904.         self.tk = master.tk
  1905.         name = None
  1906.         if cnf.has_key('name'):
  1907.             name = cnf['name']
  1908.             del cnf['name']
  1909.         if not name:
  1910.             name = repr(id(self))
  1911.         self._name = name
  1912.         if master._w=='.':
  1913.             self._w = '.' + name
  1914.         else:
  1915.             self._w = master._w + '.' + name
  1916.         self.children = {}
  1917.         if self.master.children.has_key(self._name):
  1918.             self.master.children[self._name].destroy()
  1919.         self.master.children[self._name] = self
  1920.     def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
  1921.         """Construct a widget with the parent widget MASTER, a name WIDGETNAME
  1922.         and appropriate options."""
  1923.         if kw:
  1924.             cnf = _cnfmerge((cnf, kw))
  1925.         self.widgetName = widgetName
  1926.         BaseWidget._setup(self, master, cnf)
  1927.         if self._tclCommands is None:
  1928.             self._tclCommands = []
  1929.         classes = []
  1930.         for k in cnf.keys():
  1931.             if type(k) is ClassType:
  1932.                 classes.append((k, cnf[k]))
  1933.                 del cnf[k]
  1934.         self.tk.call(
  1935.             (widgetName, self._w) + extra + self._options(cnf))
  1936.         for k, v in classes:
  1937.             k.configure(self, v)
  1938.     def destroy(self):
  1939.         """Destroy this and all descendants widgets."""
  1940.         for c in self.children.values(): c.destroy()
  1941.         self.tk.call('destroy', self._w)
  1942.         if self.master.children.has_key(self._name):
  1943.             del self.master.children[self._name]
  1944.         Misc.destroy(self)
  1945.     def _do(self, name, args=()):
  1946.         # XXX Obsolete -- better use self.tk.call directly!
  1947.         return self.tk.call((self._w, name) + args)
  1948.  
  1949. class Widget(BaseWidget, Pack, Place, Grid):
  1950.     """Internal class.
  1951.  
  1952.     Base class for a widget which can be positioned with the geometry managers
  1953.     Pack, Place or Grid."""
  1954.     pass
  1955.  
  1956. class Toplevel(BaseWidget, Wm):
  1957.     """Toplevel widget, e.g. for dialogs."""
  1958.     def __init__(self, master=None, cnf={}, **kw):
  1959.         """Construct a toplevel widget with the parent MASTER.
  1960.  
  1961.         Valid resource names: background, bd, bg, borderwidth, class,
  1962.         colormap, container, cursor, height, highlightbackground,
  1963.         highlightcolor, highlightthickness, menu, relief, screen, takefocus,
  1964.         use, visual, width."""
  1965.         if kw:
  1966.             cnf = _cnfmerge((cnf, kw))
  1967.         extra = ()
  1968.         for wmkey in ['screen', 'class_', 'class', 'visual',
  1969.                   'colormap']:
  1970.             if cnf.has_key(wmkey):
  1971.                 val = cnf[wmkey]
  1972.                 # TBD: a hack needed because some keys
  1973.                 # are not valid as keyword arguments
  1974.                 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
  1975.                 else: opt = '-'+wmkey
  1976.                 extra = extra + (opt, val)
  1977.                 del cnf[wmkey]
  1978.         BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
  1979.         root = self._root()
  1980.         self.iconname(root.iconname())
  1981.         self.title(root.title())
  1982.         self.protocol("WM_DELETE_WINDOW", self.destroy)
  1983.  
  1984. class Button(Widget):
  1985.     """Button widget."""
  1986.     def __init__(self, master=None, cnf={}, **kw):
  1987.         """Construct a button widget with the parent MASTER.
  1988.  
  1989.         STANDARD OPTIONS
  1990.  
  1991.             activebackground, activeforeground, anchor,
  1992.             background, bitmap, borderwidth, cursor,
  1993.             disabledforeground, font, foreground
  1994.             highlightbackground, highlightcolor,
  1995.             highlightthickness, image, justify,
  1996.             padx, pady, relief, repeatdelay,
  1997.             repeatinterval, takefocus, text,
  1998.             textvariable, underline, wraplength
  1999.  
  2000.         WIDGET-SPECIFIC OPTIONS
  2001.  
  2002.             command, compound, default, height,
  2003.             overrelief, state, width
  2004.         """
  2005.         Widget.__init__(self, master, 'button', cnf, kw)
  2006.  
  2007.     def tkButtonEnter(self, *dummy):
  2008.         self.tk.call('tkButtonEnter', self._w)
  2009.  
  2010.     def tkButtonLeave(self, *dummy):
  2011.         self.tk.call('tkButtonLeave', self._w)
  2012.  
  2013.     def tkButtonDown(self, *dummy):
  2014.         self.tk.call('tkButtonDown', self._w)
  2015.  
  2016.     def tkButtonUp(self, *dummy):
  2017.         self.tk.call('tkButtonUp', self._w)
  2018.  
  2019.     def tkButtonInvoke(self, *dummy):
  2020.         self.tk.call('tkButtonInvoke', self._w)
  2021.  
  2022.     def flash(self):
  2023.         """Flash the button.
  2024.  
  2025.         This is accomplished by redisplaying
  2026.         the button several times, alternating between active and
  2027.         normal colors. At the end of the flash the button is left
  2028.         in the same normal/active state as when the command was
  2029.         invoked. This command is ignored if the button's state is
  2030.         disabled.
  2031.         """
  2032.         self.tk.call(self._w, 'flash')
  2033.  
  2034.     def invoke(self):
  2035.         """Invoke the command associated with the button.
  2036.  
  2037.         The return value is the return value from the command,
  2038.         or an empty string if there is no command associated with
  2039.         the button. This command is ignored if the button's state
  2040.         is disabled.
  2041.         """
  2042.         return self.tk.call(self._w, 'invoke')
  2043.  
  2044. # Indices:
  2045. # XXX I don't like these -- take them away
  2046. def AtEnd():
  2047.     return 'end'
  2048. def AtInsert(*args):
  2049.     s = 'insert'
  2050.     for a in args:
  2051.         if a: s = s + (' ' + a)
  2052.     return s
  2053. def AtSelFirst():
  2054.     return 'sel.first'
  2055. def AtSelLast():
  2056.     return 'sel.last'
  2057. def At(x, y=None):
  2058.     if y is None:
  2059.         return '@%r' % (x,)
  2060.     else:
  2061.         return '@%r,%r' % (x, y)
  2062.  
  2063. class Canvas(Widget):
  2064.     """Canvas widget to display graphical elements like lines or text."""
  2065.     def __init__(self, master=None, cnf={}, **kw):
  2066.         """Construct a canvas widget with the parent MASTER.
  2067.  
  2068.         Valid resource names: background, bd, bg, borderwidth, closeenough,
  2069.         confine, cursor, height, highlightbackground, highlightcolor,
  2070.         highlightthickness, insertbackground, insertborderwidth,
  2071.         insertofftime, insertontime, insertwidth, offset, relief,
  2072.         scrollregion, selectbackground, selectborderwidth, selectforeground,
  2073.         state, takefocus, width, xscrollcommand, xscrollincrement,
  2074.         yscrollcommand, yscrollincrement."""
  2075.         Widget.__init__(self, master, 'canvas', cnf, kw)
  2076.     def addtag(self, *args):
  2077.         """Internal function."""
  2078.         self.tk.call((self._w, 'addtag') + args)
  2079.     def addtag_above(self, newtag, tagOrId):
  2080.         """Add tag NEWTAG to all items above TAGORID."""
  2081.         self.addtag(newtag, 'above', tagOrId)
  2082.     def addtag_all(self, newtag):
  2083.         """Add tag NEWTAG to all items."""
  2084.         self.addtag(newtag, 'all')
  2085.     def addtag_below(self, newtag, tagOrId):
  2086.         """Add tag NEWTAG to all items below TAGORID."""
  2087.         self.addtag(newtag, 'below', tagOrId)
  2088.     def addtag_closest(self, newtag, x, y, halo=None, start=None):
  2089.         """Add tag NEWTAG to item which is closest to pixel at X, Y.
  2090.         If several match take the top-most.
  2091.         All items closer than HALO are considered overlapping (all are
  2092.         closests). If START is specified the next below this tag is taken."""
  2093.         self.addtag(newtag, 'closest', x, y, halo, start)
  2094.     def addtag_enclosed(self, newtag, x1, y1, x2, y2):
  2095.         """Add tag NEWTAG to all items in the rectangle defined
  2096.         by X1,Y1,X2,Y2."""
  2097.         self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
  2098.     def addtag_overlapping(self, newtag, x1, y1, x2, y2):
  2099.         """Add tag NEWTAG to all items which overlap the rectangle
  2100.         defined by X1,Y1,X2,Y2."""
  2101.         self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
  2102.     def addtag_withtag(self, newtag, tagOrId):
  2103.         """Add tag NEWTAG to all items with TAGORID."""
  2104.         self.addtag(newtag, 'withtag', tagOrId)
  2105.     def bbox(self, *args):
  2106.         """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  2107.         which encloses all items with tags specified as arguments."""
  2108.         return self._getints(
  2109.             self.tk.call((self._w, 'bbox') + args)) or None
  2110.     def tag_unbind(self, tagOrId, sequence, funcid=None):
  2111.         """Unbind for all items with TAGORID for event SEQUENCE  the
  2112.         function identified with FUNCID."""
  2113.         self.tk.call(self._w, 'bind', tagOrId, sequence, '')
  2114.         if funcid:
  2115.             self.deletecommand(funcid)
  2116.     def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
  2117.         """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
  2118.  
  2119.         An additional boolean parameter ADD specifies whether FUNC will be
  2120.         called additionally to the other bound function or whether it will
  2121.         replace the previous function. See bind for the return value."""
  2122.         return self._bind((self._w, 'bind', tagOrId),
  2123.                   sequence, func, add)
  2124.     def canvasx(self, screenx, gridspacing=None):
  2125.         """Return the canvas x coordinate of pixel position SCREENX rounded
  2126.         to nearest multiple of GRIDSPACING units."""
  2127.         return getdouble(self.tk.call(
  2128.             self._w, 'canvasx', screenx, gridspacing))
  2129.     def canvasy(self, screeny, gridspacing=None):
  2130.         """Return the canvas y coordinate of pixel position SCREENY rounded
  2131.         to nearest multiple of GRIDSPACING units."""
  2132.         return getdouble(self.tk.call(
  2133.             self._w, 'canvasy', screeny, gridspacing))
  2134.     def coords(self, *args):
  2135.         """Return a list of coordinates for the item given in ARGS."""
  2136.         # XXX Should use _flatten on args
  2137.         return map(getdouble,
  2138.                            self.tk.splitlist(
  2139.                    self.tk.call((self._w, 'coords') + args)))
  2140.     def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
  2141.         """Internal function."""
  2142.         args = _flatten(args)
  2143.         cnf = args[-1]
  2144.         if type(cnf) in (DictionaryType, TupleType):
  2145.             args = args[:-1]
  2146.         else:
  2147.             cnf = {}
  2148.         return getint(self.tk.call(
  2149.             self._w, 'create', itemType,
  2150.             *(args + self._options(cnf, kw))))
  2151.     def create_arc(self, *args, **kw):
  2152.         """Create arc shaped region with coordinates x1,y1,x2,y2."""
  2153.         return self._create('arc', args, kw)
  2154.     def create_bitmap(self, *args, **kw):
  2155.         """Create bitmap with coordinates x1,y1."""
  2156.         return self._create('bitmap', args, kw)
  2157.     def create_image(self, *args, **kw):
  2158.         """Create image item with coordinates x1,y1."""
  2159.         return self._create('image', args, kw)
  2160.     def create_line(self, *args, **kw):
  2161.         """Create line with coordinates x1,y1,...,xn,yn."""
  2162.         return self._create('line', args, kw)
  2163.     def create_oval(self, *args, **kw):
  2164.         """Create oval with coordinates x1,y1,x2,y2."""
  2165.         return self._create('oval', args, kw)
  2166.     def create_polygon(self, *args, **kw):
  2167.         """Create polygon with coordinates x1,y1,...,xn,yn."""
  2168.         return self._create('polygon', args, kw)
  2169.     def create_rectangle(self, *args, **kw):
  2170.         """Create rectangle with coordinates x1,y1,x2,y2."""
  2171.         return self._create('rectangle', args, kw)
  2172.     def create_text(self, *args, **kw):
  2173.         """Create text with coordinates x1,y1."""
  2174.         return self._create('text', args, kw)
  2175.     def create_window(self, *args, **kw):
  2176.         """Create window with coordinates x1,y1,x2,y2."""
  2177.         return self._create('window', args, kw)
  2178.     def dchars(self, *args):
  2179.         """Delete characters of text items identified by tag or id in ARGS (possibly
  2180.         several times) from FIRST to LAST character (including)."""
  2181.         self.tk.call((self._w, 'dchars') + args)
  2182.     def delete(self, *args):
  2183.         """Delete items identified by all tag or ids contained in ARGS."""
  2184.         self.tk.call((self._w, 'delete') + args)
  2185.     def dtag(self, *args):
  2186.         """Delete tag or id given as last arguments in ARGS from items
  2187.         identified by first argument in ARGS."""
  2188.         self.tk.call((self._w, 'dtag') + args)
  2189.     def find(self, *args):
  2190.         """Internal function."""
  2191.         return self._getints(
  2192.             self.tk.call((self._w, 'find') + args)) or ()
  2193.     def find_above(self, tagOrId):
  2194.         """Return items above TAGORID."""
  2195.         return self.find('above', tagOrId)
  2196.     def find_all(self):
  2197.         """Return all items."""
  2198.         return self.find('all')
  2199.     def find_below(self, tagOrId):
  2200.         """Return all items below TAGORID."""
  2201.         return self.find('below', tagOrId)
  2202.     def find_closest(self, x, y, halo=None, start=None):
  2203.         """Return item which is closest to pixel at X, Y.
  2204.         If several match take the top-most.
  2205.         All items closer than HALO are considered overlapping (all are
  2206.         closests). If START is specified the next below this tag is taken."""
  2207.         return self.find('closest', x, y, halo, start)
  2208.     def find_enclosed(self, x1, y1, x2, y2):
  2209.         """Return all items in rectangle defined
  2210.         by X1,Y1,X2,Y2."""
  2211.         return self.find('enclosed', x1, y1, x2, y2)
  2212.     def find_overlapping(self, x1, y1, x2, y2):
  2213.         """Return all items which overlap the rectangle
  2214.         defined by X1,Y1,X2,Y2."""
  2215.         return self.find('overlapping', x1, y1, x2, y2)
  2216.     def find_withtag(self, tagOrId):
  2217.         """Return all items with TAGORID."""
  2218.         return self.find('withtag', tagOrId)
  2219.     def focus(self, *args):
  2220.         """Set focus to the first item specified in ARGS."""
  2221.         return self.tk.call((self._w, 'focus') + args)
  2222.     def gettags(self, *args):
  2223.         """Return tags associated with the first item specified in ARGS."""
  2224.         return self.tk.splitlist(
  2225.             self.tk.call((self._w, 'gettags') + args))
  2226.     def icursor(self, *args):
  2227.         """Set cursor at position POS in the item identified by TAGORID.
  2228.         In ARGS TAGORID must be first."""
  2229.         self.tk.call((self._w, 'icursor') + args)
  2230.     def index(self, *args):
  2231.         """Return position of cursor as integer in item specified in ARGS."""
  2232.         return getint(self.tk.call((self._w, 'index') + args))
  2233.     def insert(self, *args):
  2234.         """Insert TEXT in item TAGORID at position POS. ARGS must
  2235.         be TAGORID POS TEXT."""
  2236.         self.tk.call((self._w, 'insert') + args)
  2237.     def itemcget(self, tagOrId, option):
  2238.         """Return the resource value for an OPTION for item TAGORID."""
  2239.         return self.tk.call(
  2240.             (self._w, 'itemcget') + (tagOrId, '-'+option))
  2241.     def itemconfigure(self, tagOrId, cnf=None, **kw):
  2242.         """Configure resources of an item TAGORID.
  2243.  
  2244.         The values for resources are specified as keyword
  2245.         arguments. To get an overview about
  2246.         the allowed keyword arguments call the method without arguments.
  2247.         """
  2248.         return self._configure(('itemconfigure', tagOrId), cnf, kw)
  2249.     itemconfig = itemconfigure
  2250.     # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
  2251.     # so the preferred name for them is tag_lower, tag_raise
  2252.     # (similar to tag_bind, and similar to the Text widget);
  2253.     # unfortunately can't delete the old ones yet (maybe in 1.6)
  2254.     def tag_lower(self, *args):
  2255.         """Lower an item TAGORID given in ARGS
  2256.         (optional below another item)."""
  2257.         self.tk.call((self._w, 'lower') + args)
  2258.     lower = tag_lower
  2259.     def move(self, *args):
  2260.         """Move an item TAGORID given in ARGS."""
  2261.         self.tk.call((self._w, 'move') + args)
  2262.     def postscript(self, cnf={}, **kw):
  2263.         """Print the contents of the canvas to a postscript
  2264.         file. Valid options: colormap, colormode, file, fontmap,
  2265.         height, pageanchor, pageheight, pagewidth, pagex, pagey,
  2266.         rotate, witdh, x, y."""
  2267.         return self.tk.call((self._w, 'postscript') +
  2268.                     self._options(cnf, kw))
  2269.     def tag_raise(self, *args):
  2270.         """Raise an item TAGORID given in ARGS
  2271.         (optional above another item)."""
  2272.         self.tk.call((self._w, 'raise') + args)
  2273.     lift = tkraise = tag_raise
  2274.     def scale(self, *args):
  2275.         """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
  2276.         self.tk.call((self._w, 'scale') + args)
  2277.     def scan_mark(self, x, y):
  2278.         """Remember the current X, Y coordinates."""
  2279.         self.tk.call(self._w, 'scan', 'mark', x, y)
  2280.     def scan_dragto(self, x, y, gain=10):
  2281.         """Adjust the view of the canvas to GAIN times the
  2282.         difference between X and Y and the coordinates given in
  2283.         scan_mark."""
  2284.         self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
  2285.     def select_adjust(self, tagOrId, index):
  2286.         """Adjust the end of the selection near the cursor of an item TAGORID to index."""
  2287.         self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
  2288.     def select_clear(self):
  2289.         """Clear the selection if it is in this widget."""
  2290.         self.tk.call(self._w, 'select', 'clear')
  2291.     def select_from(self, tagOrId, index):
  2292.         """Set the fixed end of a selection in item TAGORID to INDEX."""
  2293.         self.tk.call(self._w, 'select', 'from', tagOrId, index)
  2294.     def select_item(self):
  2295.         """Return the item which has the selection."""
  2296.         return self.tk.call(self._w, 'select', 'item') or None
  2297.     def select_to(self, tagOrId, index):
  2298.         """Set the variable end of a selection in item TAGORID to INDEX."""
  2299.         self.tk.call(self._w, 'select', 'to', tagOrId, index)
  2300.     def type(self, tagOrId):
  2301.         """Return the type of the item TAGORID."""
  2302.         return self.tk.call(self._w, 'type', tagOrId) or None
  2303.     def xview(self, *args):
  2304.         """Query and change horizontal position of the view."""
  2305.         if not args:
  2306.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  2307.         self.tk.call((self._w, 'xview') + args)
  2308.     def xview_moveto(self, fraction):
  2309.         """Adjusts the view in the window so that FRACTION of the
  2310.         total width of the canvas is off-screen to the left."""
  2311.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  2312.     def xview_scroll(self, number, what):
  2313.         """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2314.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  2315.     def yview(self, *args):
  2316.         """Query and change vertical position of the view."""
  2317.         if not args:
  2318.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  2319.         self.tk.call((self._w, 'yview') + args)
  2320.     def yview_moveto(self, fraction):
  2321.         """Adjusts the view in the window so that FRACTION of the
  2322.         total height of the canvas is off-screen to the top."""
  2323.         self.tk.call(self._w, 'yview', 'moveto', fraction)
  2324.     def yview_scroll(self, number, what):
  2325.         """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2326.         self.tk.call(self._w, 'yview', 'scroll', number, what)
  2327.  
  2328. class Checkbutton(Widget):
  2329.     """Checkbutton widget which is either in on- or off-state."""
  2330.     def __init__(self, master=None, cnf={}, **kw):
  2331.         """Construct a checkbutton widget with the parent MASTER.
  2332.  
  2333.         Valid resource names: activebackground, activeforeground, anchor,
  2334.         background, bd, bg, bitmap, borderwidth, command, cursor,
  2335.         disabledforeground, fg, font, foreground, height,
  2336.         highlightbackground, highlightcolor, highlightthickness, image,
  2337.         indicatoron, justify, offvalue, onvalue, padx, pady, relief,
  2338.         selectcolor, selectimage, state, takefocus, text, textvariable,
  2339.         underline, variable, width, wraplength."""
  2340.         Widget.__init__(self, master, 'checkbutton', cnf, kw)
  2341.     def deselect(self):
  2342.         """Put the button in off-state."""
  2343.         self.tk.call(self._w, 'deselect')
  2344.     def flash(self):
  2345.         """Flash the button."""
  2346.         self.tk.call(self._w, 'flash')
  2347.     def invoke(self):
  2348.         """Toggle the button and invoke a command if given as resource."""
  2349.         return self.tk.call(self._w, 'invoke')
  2350.     def select(self):
  2351.         """Put the button in on-state."""
  2352.         self.tk.call(self._w, 'select')
  2353.     def toggle(self):
  2354.         """Toggle the button."""
  2355.         self.tk.call(self._w, 'toggle')
  2356.  
  2357. class Entry(Widget):
  2358.     """Entry widget which allows to display simple text."""
  2359.     def __init__(self, master=None, cnf={}, **kw):
  2360.         """Construct an entry widget with the parent MASTER.
  2361.  
  2362.         Valid resource names: background, bd, bg, borderwidth, cursor,
  2363.         exportselection, fg, font, foreground, highlightbackground,
  2364.         highlightcolor, highlightthickness, insertbackground,
  2365.         insertborderwidth, insertofftime, insertontime, insertwidth,
  2366.         invalidcommand, invcmd, justify, relief, selectbackground,
  2367.         selectborderwidth, selectforeground, show, state, takefocus,
  2368.         textvariable, validate, validatecommand, vcmd, width,
  2369.         xscrollcommand."""
  2370.         Widget.__init__(self, master, 'entry', cnf, kw)
  2371.     def delete(self, first, last=None):
  2372.         """Delete text from FIRST to LAST (not included)."""
  2373.         self.tk.call(self._w, 'delete', first, last)
  2374.     def get(self):
  2375.         """Return the text."""
  2376.         return self.tk.call(self._w, 'get')
  2377.     def icursor(self, index):
  2378.         """Insert cursor at INDEX."""
  2379.         self.tk.call(self._w, 'icursor', index)
  2380.     def index(self, index):
  2381.         """Return position of cursor."""
  2382.         return getint(self.tk.call(
  2383.             self._w, 'index', index))
  2384.     def insert(self, index, string):
  2385.         """Insert STRING at INDEX."""
  2386.         self.tk.call(self._w, 'insert', index, string)
  2387.     def scan_mark(self, x):
  2388.         """Remember the current X, Y coordinates."""
  2389.         self.tk.call(self._w, 'scan', 'mark', x)
  2390.     def scan_dragto(self, x):
  2391.         """Adjust the view of the canvas to 10 times the
  2392.         difference between X and Y and the coordinates given in
  2393.         scan_mark."""
  2394.         self.tk.call(self._w, 'scan', 'dragto', x)
  2395.     def selection_adjust(self, index):
  2396.         """Adjust the end of the selection near the cursor to INDEX."""
  2397.         self.tk.call(self._w, 'selection', 'adjust', index)
  2398.     select_adjust = selection_adjust
  2399.     def selection_clear(self):
  2400.         """Clear the selection if it is in this widget."""
  2401.         self.tk.call(self._w, 'selection', 'clear')
  2402.     select_clear = selection_clear
  2403.     def selection_from(self, index):
  2404.         """Set the fixed end of a selection to INDEX."""
  2405.         self.tk.call(self._w, 'selection', 'from', index)
  2406.     select_from = selection_from
  2407.     def selection_present(self):
  2408.         """Return whether the widget has the selection."""
  2409.         return self.tk.getboolean(
  2410.             self.tk.call(self._w, 'selection', 'present'))
  2411.     select_present = selection_present
  2412.     def selection_range(self, start, end):
  2413.         """Set the selection from START to END (not included)."""
  2414.         self.tk.call(self._w, 'selection', 'range', start, end)
  2415.     select_range = selection_range
  2416.     def selection_to(self, index):
  2417.         """Set the variable end of a selection to INDEX."""
  2418.         self.tk.call(self._w, 'selection', 'to', index)
  2419.     select_to = selection_to
  2420.     def xview(self, index):
  2421.         """Query and change horizontal position of the view."""
  2422.         self.tk.call(self._w, 'xview', index)
  2423.     def xview_moveto(self, fraction):
  2424.         """Adjust the view in the window so that FRACTION of the
  2425.         total width of the entry is off-screen to the left."""
  2426.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  2427.     def xview_scroll(self, number, what):
  2428.         """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2429.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  2430.  
  2431. class Frame(Widget):
  2432.     """Frame widget which may contain other widgets and can have a 3D border."""
  2433.     def __init__(self, master=None, cnf={}, **kw):
  2434.         """Construct a frame widget with the parent MASTER.
  2435.  
  2436.         Valid resource names: background, bd, bg, borderwidth, class,
  2437.         colormap, container, cursor, height, highlightbackground,
  2438.         highlightcolor, highlightthickness, relief, takefocus, visual, width."""
  2439.         cnf = _cnfmerge((cnf, kw))
  2440.         extra = ()
  2441.         if cnf.has_key('class_'):
  2442.             extra = ('-class', cnf['class_'])
  2443.             del cnf['class_']
  2444.         elif cnf.has_key('class'):
  2445.             extra = ('-class', cnf['class'])
  2446.             del cnf['class']
  2447.         Widget.__init__(self, master, 'frame', cnf, {}, extra)
  2448.  
  2449. class Label(Widget):
  2450.     """Label widget which can display text and bitmaps."""
  2451.     def __init__(self, master=None, cnf={}, **kw):
  2452.         """Construct a label widget with the parent MASTER.
  2453.  
  2454.         STANDARD OPTIONS
  2455.  
  2456.             activebackground, activeforeground, anchor,
  2457.             background, bitmap, borderwidth, cursor,
  2458.             disabledforeground, font, foreground,
  2459.             highlightbackground, highlightcolor,
  2460.             highlightthickness, image, justify,
  2461.             padx, pady, relief, takefocus, text,
  2462.             textvariable, underline, wraplength
  2463.  
  2464.         WIDGET-SPECIFIC OPTIONS
  2465.  
  2466.             height, state, width
  2467.  
  2468.         """
  2469.         Widget.__init__(self, master, 'label', cnf, kw)
  2470.  
  2471. class Listbox(Widget):
  2472.     """Listbox widget which can display a list of strings."""
  2473.     def __init__(self, master=None, cnf={}, **kw):
  2474.         """Construct a listbox widget with the parent MASTER.
  2475.  
  2476.         Valid resource names: background, bd, bg, borderwidth, cursor,
  2477.         exportselection, fg, font, foreground, height, highlightbackground,
  2478.         highlightcolor, highlightthickness, relief, selectbackground,
  2479.         selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
  2480.         width, xscrollcommand, yscrollcommand, listvariable."""
  2481.         Widget.__init__(self, master, 'listbox', cnf, kw)
  2482.     def activate(self, index):
  2483.         """Activate item identified by INDEX."""
  2484.         self.tk.call(self._w, 'activate', index)
  2485.     def bbox(self, *args):
  2486.         """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  2487.         which encloses the item identified by index in ARGS."""
  2488.         return self._getints(
  2489.             self.tk.call((self._w, 'bbox') + args)) or None
  2490.     def curselection(self):
  2491.         """Return list of indices of currently selected item."""
  2492.         # XXX Ought to apply self._getints()...
  2493.         return self.tk.splitlist(self.tk.call(
  2494.             self._w, 'curselection'))
  2495.     def delete(self, first, last=None):
  2496.         """Delete items from FIRST to LAST (not included)."""
  2497.         self.tk.call(self._w, 'delete', first, last)
  2498.     def get(self, first, last=None):
  2499.         """Get list of items from FIRST to LAST (not included)."""
  2500.         if last:
  2501.             return self.tk.splitlist(self.tk.call(
  2502.                 self._w, 'get', first, last))
  2503.         else:
  2504.             return self.tk.call(self._w, 'get', first)
  2505.     def index(self, index):
  2506.         """Return index of item identified with INDEX."""
  2507.         i = self.tk.call(self._w, 'index', index)
  2508.         if i == 'none': return None
  2509.         return getint(i)
  2510.     def insert(self, index, *elements):
  2511.         """Insert ELEMENTS at INDEX."""
  2512.         self.tk.call((self._w, 'insert', index) + elements)
  2513.     def nearest(self, y):
  2514.         """Get index of item which is nearest to y coordinate Y."""
  2515.         return getint(self.tk.call(
  2516.             self._w, 'nearest', y))
  2517.     def scan_mark(self, x, y):
  2518.         """Remember the current X, Y coordinates."""
  2519.         self.tk.call(self._w, 'scan', 'mark', x, y)
  2520.     def scan_dragto(self, x, y):
  2521.         """Adjust the view of the listbox to 10 times the
  2522.         difference between X and Y and the coordinates given in
  2523.         scan_mark."""
  2524.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  2525.     def see(self, index):
  2526.         """Scroll such that INDEX is visible."""
  2527.         self.tk.call(self._w, 'see', index)
  2528.     def selection_anchor(self, index):
  2529.         """Set the fixed end oft the selection to INDEX."""
  2530.         self.tk.call(self._w, 'selection', 'anchor', index)
  2531.     select_anchor = selection_anchor
  2532.     def selection_clear(self, first, last=None):
  2533.         """Clear the selection from FIRST to LAST (not included)."""
  2534.         self.tk.call(self._w,
  2535.                  'selection', 'clear', first, last)
  2536.     select_clear = selection_clear
  2537.     def selection_includes(self, index):
  2538.         """Return 1 if INDEX is part of the selection."""
  2539.         return self.tk.getboolean(self.tk.call(
  2540.             self._w, 'selection', 'includes', index))
  2541.     select_includes = selection_includes
  2542.     def selection_set(self, first, last=None):
  2543.         """Set the selection from FIRST to LAST (not included) without
  2544.         changing the currently selected elements."""
  2545.         self.tk.call(self._w, 'selection', 'set', first, last)
  2546.     select_set = selection_set
  2547.     def size(self):
  2548.         """Return the number of elements in the listbox."""
  2549.         return getint(self.tk.call(self._w, 'size'))
  2550.     def xview(self, *what):
  2551.         """Query and change horizontal position of the view."""
  2552.         if not what:
  2553.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  2554.         self.tk.call((self._w, 'xview') + what)
  2555.     def xview_moveto(self, fraction):
  2556.         """Adjust the view in the window so that FRACTION of the
  2557.         total width of the entry is off-screen to the left."""
  2558.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  2559.     def xview_scroll(self, number, what):
  2560.         """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2561.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  2562.     def yview(self, *what):
  2563.         """Query and change vertical position of the view."""
  2564.         if not what:
  2565.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  2566.         self.tk.call((self._w, 'yview') + what)
  2567.     def yview_moveto(self, fraction):
  2568.         """Adjust the view in the window so that FRACTION of the
  2569.         total width of the entry is off-screen to the top."""
  2570.         self.tk.call(self._w, 'yview', 'moveto', fraction)
  2571.     def yview_scroll(self, number, what):
  2572.         """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2573.         self.tk.call(self._w, 'yview', 'scroll', number, what)
  2574.     def itemcget(self, index, option):
  2575.         """Return the resource value for an ITEM and an OPTION."""
  2576.         return self.tk.call(
  2577.             (self._w, 'itemcget') + (index, '-'+option))
  2578.     def itemconfigure(self, index, cnf=None, **kw):
  2579.         """Configure resources of an ITEM.
  2580.  
  2581.         The values for resources are specified as keyword arguments.
  2582.         To get an overview about the allowed keyword arguments
  2583.         call the method without arguments.
  2584.         Valid resource names: background, bg, foreground, fg,
  2585.         selectbackground, selectforeground."""
  2586.         return self._configure(('itemconfigure', index), cnf, kw)
  2587.     itemconfig = itemconfigure
  2588.  
  2589. class Menu(Widget):
  2590.     """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
  2591.     def __init__(self, master=None, cnf={}, **kw):
  2592.         """Construct menu widget with the parent MASTER.
  2593.  
  2594.         Valid resource names: activebackground, activeborderwidth,
  2595.         activeforeground, background, bd, bg, borderwidth, cursor,
  2596.         disabledforeground, fg, font, foreground, postcommand, relief,
  2597.         selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
  2598.         Widget.__init__(self, master, 'menu', cnf, kw)
  2599.     def tk_bindForTraversal(self):
  2600.         pass # obsolete since Tk 4.0
  2601.     def tk_mbPost(self):
  2602.         self.tk.call('tk_mbPost', self._w)
  2603.     def tk_mbUnpost(self):
  2604.         self.tk.call('tk_mbUnpost')
  2605.     def tk_traverseToMenu(self, char):
  2606.         self.tk.call('tk_traverseToMenu', self._w, char)
  2607.     def tk_traverseWithinMenu(self, char):
  2608.         self.tk.call('tk_traverseWithinMenu', self._w, char)
  2609.     def tk_getMenuButtons(self):
  2610.         return self.tk.call('tk_getMenuButtons', self._w)
  2611.     def tk_nextMenu(self, count):
  2612.         self.tk.call('tk_nextMenu', count)
  2613.     def tk_nextMenuEntry(self, count):
  2614.         self.tk.call('tk_nextMenuEntry', count)
  2615.     def tk_invokeMenu(self):
  2616.         self.tk.call('tk_invokeMenu', self._w)
  2617.     def tk_firstMenu(self):
  2618.         self.tk.call('tk_firstMenu', self._w)
  2619.     def tk_mbButtonDown(self):
  2620.         self.tk.call('tk_mbButtonDown', self._w)
  2621.     def tk_popup(self, x, y, entry=""):
  2622.         """Post the menu at position X,Y with entry ENTRY."""
  2623.         self.tk.call('tk_popup', self._w, x, y, entry)
  2624.     def activate(self, index):
  2625.         """Activate entry at INDEX."""
  2626.         self.tk.call(self._w, 'activate', index)
  2627.     def add(self, itemType, cnf={}, **kw):
  2628.         """Internal function."""
  2629.         self.tk.call((self._w, 'add', itemType) +
  2630.                  self._options(cnf, kw))
  2631.     def add_cascade(self, cnf={}, **kw):
  2632.         """Add hierarchical menu item."""
  2633.         self.add('cascade', cnf or kw)
  2634.     def add_checkbutton(self, cnf={}, **kw):
  2635.         """Add checkbutton menu item."""
  2636.         self.add('checkbutton', cnf or kw)
  2637.     def add_command(self, cnf={}, **kw):
  2638.         """Add command menu item."""
  2639.         self.add('command', cnf or kw)
  2640.     def add_radiobutton(self, cnf={}, **kw):
  2641.         """Addd radio menu item."""
  2642.         self.add('radiobutton', cnf or kw)
  2643.     def add_separator(self, cnf={}, **kw):
  2644.         """Add separator."""
  2645.         self.add('separator', cnf or kw)
  2646.     def insert(self, index, itemType, cnf={}, **kw):
  2647.         """Internal function."""
  2648.         self.tk.call((self._w, 'insert', index, itemType) +
  2649.                  self._options(cnf, kw))
  2650.     def insert_cascade(self, index, cnf={}, **kw):
  2651.         """Add hierarchical menu item at INDEX."""
  2652.         self.insert(index, 'cascade', cnf or kw)
  2653.     def insert_checkbutton(self, index, cnf={}, **kw):
  2654.         """Add checkbutton menu item at INDEX."""
  2655.         self.insert(index, 'checkbutton', cnf or kw)
  2656.     def insert_command(self, index, cnf={}, **kw):
  2657.         """Add command menu item at INDEX."""
  2658.         self.insert(index, 'command', cnf or kw)
  2659.     def insert_radiobutton(self, index, cnf={}, **kw):
  2660.         """Addd radio menu item at INDEX."""
  2661.         self.insert(index, 'radiobutton', cnf or kw)
  2662.     def insert_separator(self, index, cnf={}, **kw):
  2663.         """Add separator at INDEX."""
  2664.         self.insert(index, 'separator', cnf or kw)
  2665.     def delete(self, index1, index2=None):
  2666.         """Delete menu items between INDEX1 and INDEX2 (included)."""
  2667.         if index2 is None:
  2668.             index2 = index1
  2669.  
  2670.         num_index1, num_index2 = self.index(index1), self.index(index2)
  2671.         if (num_index1 is None) or (num_index2 is None):
  2672.             num_index1, num_index2 = 0, -1
  2673.  
  2674.         for i in range(num_index1, num_index2 + 1):
  2675.             if 'command' in self.entryconfig(i):
  2676.                 c = str(self.entrycget(i, 'command'))
  2677.                 if c:
  2678.                     self.deletecommand(c)
  2679.         self.tk.call(self._w, 'delete', index1, index2)
  2680.     def entrycget(self, index, option):
  2681.         """Return the resource value of an menu item for OPTION at INDEX."""
  2682.         return self.tk.call(self._w, 'entrycget', index, '-' + option)
  2683.     def entryconfigure(self, index, cnf=None, **kw):
  2684.         """Configure a menu item at INDEX."""
  2685.         return self._configure(('entryconfigure', index), cnf, kw)
  2686.     entryconfig = entryconfigure
  2687.     def index(self, index):
  2688.         """Return the index of a menu item identified by INDEX."""
  2689.         i = self.tk.call(self._w, 'index', index)
  2690.         if i == 'none': return None
  2691.         return getint(i)
  2692.     def invoke(self, index):
  2693.         """Invoke a menu item identified by INDEX and execute
  2694.         the associated command."""
  2695.         return self.tk.call(self._w, 'invoke', index)
  2696.     def post(self, x, y):
  2697.         """Display a menu at position X,Y."""
  2698.         self.tk.call(self._w, 'post', x, y)
  2699.     def type(self, index):
  2700.         """Return the type of the menu item at INDEX."""
  2701.         return self.tk.call(self._w, 'type', index)
  2702.     def unpost(self):
  2703.         """Unmap a menu."""
  2704.         self.tk.call(self._w, 'unpost')
  2705.     def yposition(self, index):
  2706.         """Return the y-position of the topmost pixel of the menu item at INDEX."""
  2707.         return getint(self.tk.call(
  2708.             self._w, 'yposition', index))
  2709.  
  2710. class Menubutton(Widget):
  2711.     """Menubutton widget, obsolete since Tk8.0."""
  2712.     def __init__(self, master=None, cnf={}, **kw):
  2713.         Widget.__init__(self, master, 'menubutton', cnf, kw)
  2714.  
  2715. class Message(Widget):
  2716.     """Message widget to display multiline text. Obsolete since Label does it too."""
  2717.     def __init__(self, master=None, cnf={}, **kw):
  2718.         Widget.__init__(self, master, 'message', cnf, kw)
  2719.  
  2720. class Radiobutton(Widget):
  2721.     """Radiobutton widget which shows only one of several buttons in on-state."""
  2722.     def __init__(self, master=None, cnf={}, **kw):
  2723.         """Construct a radiobutton widget with the parent MASTER.
  2724.  
  2725.         Valid resource names: activebackground, activeforeground, anchor,
  2726.         background, bd, bg, bitmap, borderwidth, command, cursor,
  2727.         disabledforeground, fg, font, foreground, height,
  2728.         highlightbackground, highlightcolor, highlightthickness, image,
  2729.         indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
  2730.         state, takefocus, text, textvariable, underline, value, variable,
  2731.         width, wraplength."""
  2732.         Widget.__init__(self, master, 'radiobutton', cnf, kw)
  2733.     def deselect(self):
  2734.         """Put the button in off-state."""
  2735.  
  2736.         self.tk.call(self._w, 'deselect')
  2737.     def flash(self):
  2738.         """Flash the button."""
  2739.         self.tk.call(self._w, 'flash')
  2740.     def invoke(self):
  2741.         """Toggle the button and invoke a command if given as resource."""
  2742.         return self.tk.call(self._w, 'invoke')
  2743.     def select(self):
  2744.         """Put the button in on-state."""
  2745.         self.tk.call(self._w, 'select')
  2746.  
  2747. class Scale(Widget):
  2748.     """Scale widget which can display a numerical scale."""
  2749.     def __init__(self, master=None, cnf={}, **kw):
  2750.         """Construct a scale widget with the parent MASTER.
  2751.  
  2752.         Valid resource names: activebackground, background, bigincrement, bd,
  2753.         bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
  2754.         highlightbackground, highlightcolor, highlightthickness, label,
  2755.         length, orient, relief, repeatdelay, repeatinterval, resolution,
  2756.         showvalue, sliderlength, sliderrelief, state, takefocus,
  2757.         tickinterval, to, troughcolor, variable, width."""
  2758.         Widget.__init__(self, master, 'scale', cnf, kw)
  2759.     def get(self):
  2760.         """Get the current value as integer or float."""
  2761.         value = self.tk.call(self._w, 'get')
  2762.         try:
  2763.             return getint(value)
  2764.         except ValueError:
  2765.             return getdouble(value)
  2766.     def set(self, value):
  2767.         """Set the value to VALUE."""
  2768.         self.tk.call(self._w, 'set', value)
  2769.     def coords(self, value=None):
  2770.         """Return a tuple (X,Y) of the point along the centerline of the
  2771.         trough that corresponds to VALUE or the current value if None is
  2772.         given."""
  2773.  
  2774.         return self._getints(self.tk.call(self._w, 'coords', value))
  2775.     def identify(self, x, y):
  2776.         """Return where the point X,Y lies. Valid return values are "slider",
  2777.         "though1" and "though2"."""
  2778.         return self.tk.call(self._w, 'identify', x, y)
  2779.  
  2780. class Scrollbar(Widget):
  2781.     """Scrollbar widget which displays a slider at a certain position."""
  2782.     def __init__(self, master=None, cnf={}, **kw):
  2783.         """Construct a scrollbar widget with the parent MASTER.
  2784.  
  2785.         Valid resource names: activebackground, activerelief,
  2786.         background, bd, bg, borderwidth, command, cursor,
  2787.         elementborderwidth, highlightbackground,
  2788.         highlightcolor, highlightthickness, jump, orient,
  2789.         relief, repeatdelay, repeatinterval, takefocus,
  2790.         troughcolor, width."""
  2791.         Widget.__init__(self, master, 'scrollbar', cnf, kw)
  2792.     def activate(self, index):
  2793.         """Display the element at INDEX with activebackground and activerelief.
  2794.         INDEX can be "arrow1","slider" or "arrow2"."""
  2795.         self.tk.call(self._w, 'activate', index)
  2796.     def delta(self, deltax, deltay):
  2797.         """Return the fractional change of the scrollbar setting if it
  2798.         would be moved by DELTAX or DELTAY pixels."""
  2799.         return getdouble(
  2800.             self.tk.call(self._w, 'delta', deltax, deltay))
  2801.     def fraction(self, x, y):
  2802.         """Return the fractional value which corresponds to a slider
  2803.         position of X,Y."""
  2804.         return getdouble(self.tk.call(self._w, 'fraction', x, y))
  2805.     def identify(self, x, y):
  2806.         """Return the element under position X,Y as one of
  2807.         "arrow1","slider","arrow2" or ""."""
  2808.         return self.tk.call(self._w, 'identify', x, y)
  2809.     def get(self):
  2810.         """Return the current fractional values (upper and lower end)
  2811.         of the slider position."""
  2812.         return self._getdoubles(self.tk.call(self._w, 'get'))
  2813.     def set(self, *args):
  2814.         """Set the fractional values of the slider position (upper and
  2815.         lower ends as value between 0 and 1)."""
  2816.         self.tk.call((self._w, 'set') + args)
  2817.  
  2818.  
  2819.  
  2820. class Text(Widget):
  2821.     """Text widget which can display text in various forms."""
  2822.     def __init__(self, master=None, cnf={}, **kw):
  2823.         """Construct a text widget with the parent MASTER.
  2824.  
  2825.         STANDARD OPTIONS
  2826.  
  2827.             background, borderwidth, cursor,
  2828.             exportselection, font, foreground,
  2829.             highlightbackground, highlightcolor,
  2830.             highlightthickness, insertbackground,
  2831.             insertborderwidth, insertofftime,
  2832.             insertontime, insertwidth, padx, pady,
  2833.             relief, selectbackground,
  2834.             selectborderwidth, selectforeground,
  2835.             setgrid, takefocus,
  2836.             xscrollcommand, yscrollcommand,
  2837.  
  2838.         WIDGET-SPECIFIC OPTIONS
  2839.  
  2840.             autoseparators, height, maxundo,
  2841.             spacing1, spacing2, spacing3,
  2842.             state, tabs, undo, width, wrap,
  2843.  
  2844.         """
  2845.         Widget.__init__(self, master, 'text', cnf, kw)
  2846.     def bbox(self, *args):
  2847.         """Return a tuple of (x,y,width,height) which gives the bounding
  2848.         box of the visible part of the character at the index in ARGS."""
  2849.         return self._getints(
  2850.             self.tk.call((self._w, 'bbox') + args)) or None
  2851.     def tk_textSelectTo(self, index):
  2852.         self.tk.call('tk_textSelectTo', self._w, index)
  2853.     def tk_textBackspace(self):
  2854.         self.tk.call('tk_textBackspace', self._w)
  2855.     def tk_textIndexCloser(self, a, b, c):
  2856.         self.tk.call('tk_textIndexCloser', self._w, a, b, c)
  2857.     def tk_textResetAnchor(self, index):
  2858.         self.tk.call('tk_textResetAnchor', self._w, index)
  2859.     def compare(self, index1, op, index2):
  2860.         """Return whether between index INDEX1 and index INDEX2 the
  2861.         relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
  2862.         return self.tk.getboolean(self.tk.call(
  2863.             self._w, 'compare', index1, op, index2))
  2864.     def debug(self, boolean=None):
  2865.         """Turn on the internal consistency checks of the B-Tree inside the text
  2866.         widget according to BOOLEAN."""
  2867.         return self.tk.getboolean(self.tk.call(
  2868.             self._w, 'debug', boolean))
  2869.     def delete(self, index1, index2=None):
  2870.         """Delete the characters between INDEX1 and INDEX2 (not included)."""
  2871.         self.tk.call(self._w, 'delete', index1, index2)
  2872.     def dlineinfo(self, index):
  2873.         """Return tuple (x,y,width,height,baseline) giving the bounding box
  2874.         and baseline position of the visible part of the line containing
  2875.         the character at INDEX."""
  2876.         return self._getints(self.tk.call(self._w, 'dlineinfo', index))
  2877.     def dump(self, index1, index2=None, command=None, **kw):
  2878.         """Return the contents of the widget between index1 and index2.
  2879.  
  2880.         The type of contents returned in filtered based on the keyword
  2881.         parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
  2882.         given and true, then the corresponding items are returned. The result
  2883.         is a list of triples of the form (key, value, index). If none of the
  2884.         keywords are true then 'all' is used by default.
  2885.  
  2886.         If the 'command' argument is given, it is called once for each element
  2887.         of the list of triples, with the values of each triple serving as the
  2888.         arguments to the function. In this case the list is not returned."""
  2889.         args = []
  2890.         func_name = None
  2891.         result = None
  2892.         if not command:
  2893.             # Never call the dump command without the -command flag, since the
  2894.             # output could involve Tcl quoting and would be a pain to parse
  2895.             # right. Instead just set the command to build a list of triples
  2896.             # as if we had done the parsing.
  2897.             result = []
  2898.             def append_triple(key, value, index, result=result):
  2899.                 result.append((key, value, index))
  2900.             command = append_triple
  2901.         try:
  2902.             if not isinstance(command, str):
  2903.                 func_name = command = self._register(command)
  2904.             args += ["-command", command]
  2905.             for key in kw:
  2906.                 if kw[key]: args.append("-" + key)
  2907.             args.append(index1)
  2908.             if index2:
  2909.                 args.append(index2)
  2910.             self.tk.call(self._w, "dump", *args)
  2911.             return result
  2912.         finally:
  2913.             if func_name:
  2914.                 self.deletecommand(func_name)
  2915.  
  2916.     ## new in tk8.4
  2917.     def edit(self, *args):
  2918.         """Internal method
  2919.  
  2920.         This method controls the undo mechanism and
  2921.         the modified flag. The exact behavior of the
  2922.         command depends on the option argument that
  2923.         follows the edit argument. The following forms
  2924.         of the command are currently supported:
  2925.  
  2926.         edit_modified, edit_redo, edit_reset, edit_separator
  2927.         and edit_undo
  2928.  
  2929.         """
  2930.         return self.tk.call(self._w, 'edit', *args)
  2931.  
  2932.     def edit_modified(self, arg=None):
  2933.         """Get or Set the modified flag
  2934.  
  2935.         If arg is not specified, returns the modified
  2936.         flag of the widget. The insert, delete, edit undo and
  2937.         edit redo commands or the user can set or clear the
  2938.         modified flag. If boolean is specified, sets the
  2939.         modified flag of the widget to arg.
  2940.         """
  2941.         return self.edit("modified", arg)
  2942.  
  2943.     def edit_redo(self):
  2944.         """Redo the last undone edit
  2945.  
  2946.         When the undo option is true, reapplies the last
  2947.         undone edits provided no other edits were done since
  2948.         then. Generates an error when the redo stack is empty.
  2949.         Does nothing when the undo option is false.
  2950.         """
  2951.         return self.edit("redo")
  2952.  
  2953.     def edit_reset(self):
  2954.         """Clears the undo and redo stacks
  2955.         """
  2956.         return self.edit("reset")
  2957.  
  2958.     def edit_separator(self):
  2959.         """Inserts a separator (boundary) on the undo stack.
  2960.  
  2961.         Does nothing when the undo option is false
  2962.         """
  2963.         return self.edit("separator")
  2964.  
  2965.     def edit_undo(self):
  2966.         """Undoes the last edit action
  2967.  
  2968.         If the undo option is true. An edit action is defined
  2969.         as all the insert and delete commands that are recorded
  2970.         on the undo stack in between two separators. Generates
  2971.         an error when the undo stack is empty. Does nothing
  2972.         when the undo option is false
  2973.         """
  2974.         return self.edit("undo")
  2975.  
  2976.     def get(self, index1, index2=None):
  2977.         """Return the text from INDEX1 to INDEX2 (not included)."""
  2978.         return self.tk.call(self._w, 'get', index1, index2)
  2979.     # (Image commands are new in 8.0)
  2980.     def image_cget(self, index, option):
  2981.         """Return the value of OPTION of an embedded image at INDEX."""
  2982.         if option[:1] != "-":
  2983.             option = "-" + option
  2984.         if option[-1:] == "_":
  2985.             option = option[:-1]
  2986.         return self.tk.call(self._w, "image", "cget", index, option)
  2987.     def image_configure(self, index, cnf=None, **kw):
  2988.         """Configure an embedded image at INDEX."""
  2989.         return self._configure(('image', 'configure', index), cnf, kw)
  2990.     def image_create(self, index, cnf={}, **kw):
  2991.         """Create an embedded image at INDEX."""
  2992.         return self.tk.call(
  2993.                  self._w, "image", "create", index,
  2994.                  *self._options(cnf, kw))
  2995.     def image_names(self):
  2996.         """Return all names of embedded images in this widget."""
  2997.         return self.tk.call(self._w, "image", "names")
  2998.     def index(self, index):
  2999.         """Return the index in the form line.char for INDEX."""
  3000.         return str(self.tk.call(self._w, 'index', index))
  3001.     def insert(self, index, chars, *args):
  3002.         """Insert CHARS before the characters at INDEX. An additional
  3003.         tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
  3004.         self.tk.call((self._w, 'insert', index, chars) + args)
  3005.     def mark_gravity(self, markName, direction=None):
  3006.         """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
  3007.         Return the current value if None is given for DIRECTION."""
  3008.         return self.tk.call(
  3009.             (self._w, 'mark', 'gravity', markName, direction))
  3010.     def mark_names(self):
  3011.         """Return all mark names."""
  3012.         return self.tk.splitlist(self.tk.call(
  3013.             self._w, 'mark', 'names'))
  3014.     def mark_set(self, markName, index):
  3015.         """Set mark MARKNAME before the character at INDEX."""
  3016.         self.tk.call(self._w, 'mark', 'set', markName, index)
  3017.     def mark_unset(self, *markNames):
  3018.         """Delete all marks in MARKNAMES."""
  3019.         self.tk.call((self._w, 'mark', 'unset') + markNames)
  3020.     def mark_next(self, index):
  3021.         """Return the name of the next mark after INDEX."""
  3022.         return self.tk.call(self._w, 'mark', 'next', index) or None
  3023.     def mark_previous(self, index):
  3024.         """Return the name of the previous mark before INDEX."""
  3025.         return self.tk.call(self._w, 'mark', 'previous', index) or None
  3026.     def scan_mark(self, x, y):
  3027.         """Remember the current X, Y coordinates."""
  3028.         self.tk.call(self._w, 'scan', 'mark', x, y)
  3029.     def scan_dragto(self, x, y):
  3030.         """Adjust the view of the text to 10 times the
  3031.         difference between X and Y and the coordinates given in
  3032.         scan_mark."""
  3033.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  3034.     def search(self, pattern, index, stopindex=None,
  3035.            forwards=None, backwards=None, exact=None,
  3036.            regexp=None, nocase=None, count=None, elide=None):
  3037.         """Search PATTERN beginning from INDEX until STOPINDEX.
  3038.         Return the index of the first character of a match or an
  3039.         empty string."""
  3040.         args = [self._w, 'search']
  3041.         if forwards: args.append('-forwards')
  3042.         if backwards: args.append('-backwards')
  3043.         if exact: args.append('-exact')
  3044.         if regexp: args.append('-regexp')
  3045.         if nocase: args.append('-nocase')
  3046.         if elide: args.append('-elide')
  3047.         if count: args.append('-count'); args.append(count)
  3048.         if pattern and pattern[0] == '-': args.append('--')
  3049.         args.append(pattern)
  3050.         args.append(index)
  3051.         if stopindex: args.append(stopindex)
  3052.         return str(self.tk.call(tuple(args)))
  3053.     def see(self, index):
  3054.         """Scroll such that the character at INDEX is visible."""
  3055.         self.tk.call(self._w, 'see', index)
  3056.     def tag_add(self, tagName, index1, *args):
  3057.         """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
  3058.         Additional pairs of indices may follow in ARGS."""
  3059.         self.tk.call(
  3060.             (self._w, 'tag', 'add', tagName, index1) + args)
  3061.     def tag_unbind(self, tagName, sequence, funcid=None):
  3062.         """Unbind for all characters with TAGNAME for event SEQUENCE  the
  3063.         function identified with FUNCID."""
  3064.         self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
  3065.         if funcid:
  3066.             self.deletecommand(funcid)
  3067.     def tag_bind(self, tagName, sequence, func, add=None):
  3068.         """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
  3069.  
  3070.         An additional boolean parameter ADD specifies whether FUNC will be
  3071.         called additionally to the other bound function or whether it will
  3072.         replace the previous function. See bind for the return value."""
  3073.         return self._bind((self._w, 'tag', 'bind', tagName),
  3074.                   sequence, func, add)
  3075.     def tag_cget(self, tagName, option):
  3076.         """Return the value of OPTION for tag TAGNAME."""
  3077.         if option[:1] != '-':
  3078.             option = '-' + option
  3079.         if option[-1:] == '_':
  3080.             option = option[:-1]
  3081.         return self.tk.call(self._w, 'tag', 'cget', tagName, option)
  3082.     def tag_configure(self, tagName, cnf=None, **kw):
  3083.         """Configure a tag TAGNAME."""
  3084.         return self._configure(('tag', 'configure', tagName), cnf, kw)
  3085.     tag_config = tag_configure
  3086.     def tag_delete(self, *tagNames):
  3087.         """Delete all tags in TAGNAMES."""
  3088.         self.tk.call((self._w, 'tag', 'delete') + tagNames)
  3089.     def tag_lower(self, tagName, belowThis=None):
  3090.         """Change the priority of tag TAGNAME such that it is lower
  3091.         than the priority of BELOWTHIS."""
  3092.         self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
  3093.     def tag_names(self, index=None):
  3094.         """Return a list of all tag names."""
  3095.         return self.tk.splitlist(
  3096.             self.tk.call(self._w, 'tag', 'names', index))
  3097.     def tag_nextrange(self, tagName, index1, index2=None):
  3098.         """Return a list of start and end index for the first sequence of
  3099.         characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  3100.         The text is searched forward from INDEX1."""
  3101.         return self.tk.splitlist(self.tk.call(
  3102.             self._w, 'tag', 'nextrange', tagName, index1, index2))
  3103.     def tag_prevrange(self, tagName, index1, index2=None):
  3104.         """Return a list of start and end index for the first sequence of
  3105.         characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  3106.         The text is searched backwards from INDEX1."""
  3107.         return self.tk.splitlist(self.tk.call(
  3108.             self._w, 'tag', 'prevrange', tagName, index1, index2))
  3109.     def tag_raise(self, tagName, aboveThis=None):
  3110.         """Change the priority of tag TAGNAME such that it is higher
  3111.         than the priority of ABOVETHIS."""
  3112.         self.tk.call(
  3113.             self._w, 'tag', 'raise', tagName, aboveThis)
  3114.     def tag_ranges(self, tagName):
  3115.         """Return a list of ranges of text which have tag TAGNAME."""
  3116.         return self.tk.splitlist(self.tk.call(
  3117.             self._w, 'tag', 'ranges', tagName))
  3118.     def tag_remove(self, tagName, index1, index2=None):
  3119.         """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
  3120.         self.tk.call(
  3121.             self._w, 'tag', 'remove', tagName, index1, index2)
  3122.     def window_cget(self, index, option):
  3123.         """Return the value of OPTION of an embedded window at INDEX."""
  3124.         if option[:1] != '-':
  3125.             option = '-' + option
  3126.         if option[-1:] == '_':
  3127.             option = option[:-1]
  3128.         return self.tk.call(self._w, 'window', 'cget', index, option)
  3129.     def window_configure(self, index, cnf=None, **kw):
  3130.         """Configure an embedded window at INDEX."""
  3131.         return self._configure(('window', 'configure', index), cnf, kw)
  3132.     window_config = window_configure
  3133.     def window_create(self, index, cnf={}, **kw):
  3134.         """Create a window at INDEX."""
  3135.         self.tk.call(
  3136.               (self._w, 'window', 'create', index)
  3137.               + self._options(cnf, kw))
  3138.     def window_names(self):
  3139.         """Return all names of embedded windows in this widget."""
  3140.         return self.tk.splitlist(
  3141.             self.tk.call(self._w, 'window', 'names'))
  3142.     def xview(self, *what):
  3143.         """Query and change horizontal position of the view."""
  3144.         if not what:
  3145.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  3146.         self.tk.call((self._w, 'xview') + what)
  3147.     def xview_moveto(self, fraction):
  3148.         """Adjusts the view in the window so that FRACTION of the
  3149.         total width of the canvas is off-screen to the left."""
  3150.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  3151.     def xview_scroll(self, number, what):
  3152.         """Shift the x-view according to NUMBER which is measured
  3153.         in "units" or "pages" (WHAT)."""
  3154.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  3155.     def yview(self, *what):
  3156.         """Query and change vertical position of the view."""
  3157.         if not what:
  3158.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  3159.         self.tk.call((self._w, 'yview') + what)
  3160.     def yview_moveto(self, fraction):
  3161.         """Adjusts the view in the window so that FRACTION of the
  3162.         total height of the canvas is off-screen to the top."""
  3163.         self.tk.call(self._w, 'yview', 'moveto', fraction)
  3164.     def yview_scroll(self, number, what):
  3165.         """Shift the y-view according to NUMBER which is measured
  3166.         in "units" or "pages" (WHAT)."""
  3167.         self.tk.call(self._w, 'yview', 'scroll', number, what)
  3168.     def yview_pickplace(self, *what):
  3169.         """Obsolete function, use see."""
  3170.         self.tk.call((self._w, 'yview', '-pickplace') + what)
  3171.  
  3172.  
  3173. class _setit:
  3174.     """Internal class. It wraps the command in the widget OptionMenu."""
  3175.     def __init__(self, var, value, callback=None):
  3176.         self.__value = value
  3177.         self.__var = var
  3178.         self.__callback = callback
  3179.     def __call__(self, *args):
  3180.         self.__var.set(self.__value)
  3181.         if self.__callback:
  3182.             self.__callback(self.__value, *args)
  3183.  
  3184. class OptionMenu(Menubutton):
  3185.     """OptionMenu which allows the user to select a value from a menu."""
  3186.     def __init__(self, master, variable, value, *values, **kwargs):
  3187.         """Construct an optionmenu widget with the parent MASTER, with
  3188.         the resource textvariable set to VARIABLE, the initially selected
  3189.         value VALUE, the other menu values VALUES and an additional
  3190.         keyword argument command."""
  3191.         kw = {"borderwidth": 2, "textvariable": variable,
  3192.               "indicatoron": 1, "relief": RAISED, "anchor": "c",
  3193.               "highlightthickness": 2}
  3194.         Widget.__init__(self, master, "menubutton", kw)
  3195.         self.widgetName = 'tk_optionMenu'
  3196.         menu = self.__menu = Menu(self, name="menu", tearoff=0)
  3197.         self.menuname = menu._w
  3198.         # 'command' is the only supported keyword
  3199.         callback = kwargs.get('command')
  3200.         if kwargs.has_key('command'):
  3201.             del kwargs['command']
  3202.         if kwargs:
  3203.             raise TclError, 'unknown option -'+kwargs.keys()[0]
  3204.         menu.add_command(label=value,
  3205.                  command=_setit(variable, value, callback))
  3206.         for v in values:
  3207.             menu.add_command(label=v,
  3208.                      command=_setit(variable, v, callback))
  3209.         self["menu"] = menu
  3210.  
  3211.     def __getitem__(self, name):
  3212.         if name == 'menu':
  3213.             return self.__menu
  3214.         return Widget.__getitem__(self, name)
  3215.  
  3216.     def destroy(self):
  3217.         """Destroy this widget and the associated menu."""
  3218.         Menubutton.destroy(self)
  3219.         self.__menu = None
  3220.  
  3221. class Image:
  3222.     """Base class for images."""
  3223.     _last_id = 0
  3224.     def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
  3225.         self.name = None
  3226.         if not master:
  3227.             master = _default_root
  3228.             if not master:
  3229.                 raise RuntimeError, 'Too early to create image'
  3230.         self.tk = master.tk
  3231.         if not name:
  3232.             Image._last_id += 1
  3233.             name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
  3234.             # The following is needed for systems where id(x)
  3235.             # can return a negative number, such as Linux/m68k:
  3236.             if name[0] == '-': name = '_' + name[1:]
  3237.         if kw and cnf: cnf = _cnfmerge((cnf, kw))
  3238.         elif kw: cnf = kw
  3239.         options = ()
  3240.         for k, v in cnf.items():
  3241.             if callable(v):
  3242.                 v = self._register(v)
  3243.             options = options + ('-'+k, v)
  3244.         self.tk.call(('image', 'create', imgtype, name,) + options)
  3245.         self.name = name
  3246.     def __str__(self): return self.name
  3247.     def __del__(self):
  3248.         if self.name:
  3249.             try:
  3250.                 self.tk.call('image', 'delete', self.name)
  3251.             except TclError:
  3252.                 # May happen if the root was destroyed
  3253.                 pass
  3254.     def __setitem__(self, key, value):
  3255.         self.tk.call(self.name, 'configure', '-'+key, value)
  3256.     def __getitem__(self, key):
  3257.         return self.tk.call(self.name, 'configure', '-'+key)
  3258.     def configure(self, **kw):
  3259.         """Configure the image."""
  3260.         res = ()
  3261.         for k, v in _cnfmerge(kw).items():
  3262.             if v is not None:
  3263.                 if k[-1] == '_': k = k[:-1]
  3264.                 if callable(v):
  3265.                     v = self._register(v)
  3266.                 res = res + ('-'+k, v)
  3267.         self.tk.call((self.name, 'config') + res)
  3268.     config = configure
  3269.     def height(self):
  3270.         """Return the height of the image."""
  3271.         return getint(
  3272.             self.tk.call('image', 'height', self.name))
  3273.     def type(self):
  3274.         """Return the type of the imgage, e.g. "photo" or "bitmap"."""
  3275.         return self.tk.call('image', 'type', self.name)
  3276.     def width(self):
  3277.         """Return the width of the image."""
  3278.         return getint(
  3279.             self.tk.call('image', 'width', self.name))
  3280.  
  3281. class PhotoImage(Image):
  3282.     """Widget which can display colored images in GIF, PPM/PGM format."""
  3283.     def __init__(self, name=None, cnf={}, master=None, **kw):
  3284.         """Create an image with NAME.
  3285.  
  3286.         Valid resource names: data, format, file, gamma, height, palette,
  3287.         width."""
  3288.         Image.__init__(self, 'photo', name, cnf, master, **kw)
  3289.     def blank(self):
  3290.         """Display a transparent image."""
  3291.         self.tk.call(self.name, 'blank')
  3292.     def cget(self, option):
  3293.         """Return the value of OPTION."""
  3294.         return self.tk.call(self.name, 'cget', '-' + option)
  3295.     # XXX config
  3296.     def __getitem__(self, key):
  3297.         return self.tk.call(self.name, 'cget', '-' + key)
  3298.     # XXX copy -from, -to, ...?
  3299.     def copy(self):
  3300.         """Return a new PhotoImage with the same image as this widget."""
  3301.         destImage = PhotoImage()
  3302.         self.tk.call(destImage, 'copy', self.name)
  3303.         return destImage
  3304.     def zoom(self,x,y=''):
  3305.         """Return a new PhotoImage with the same image as this widget
  3306.         but zoom it with X and Y."""
  3307.         destImage = PhotoImage()
  3308.         if y=='': y=x
  3309.         self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
  3310.         return destImage
  3311.     def subsample(self,x,y=''):
  3312.         """Return a new PhotoImage based on the same image as this widget
  3313.         but use only every Xth or Yth pixel."""
  3314.         destImage = PhotoImage()
  3315.         if y=='': y=x
  3316.         self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
  3317.         return destImage
  3318.     def get(self, x, y):
  3319.         """Return the color (red, green, blue) of the pixel at X,Y."""
  3320.         return self.tk.call(self.name, 'get', x, y)
  3321.     def put(self, data, to=None):
  3322.         """Put row formatted colors to image starting from
  3323.         position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
  3324.         args = (self.name, 'put', data)
  3325.         if to:
  3326.             if to[0] == '-to':
  3327.                 to = to[1:]
  3328.             args = args + ('-to',) + tuple(to)
  3329.         self.tk.call(args)
  3330.     # XXX read
  3331.     def write(self, filename, format=None, from_coords=None):
  3332.         """Write image to file FILENAME in FORMAT starting from
  3333.         position FROM_COORDS."""
  3334.         args = (self.name, 'write', filename)
  3335.         if format:
  3336.             args = args + ('-format', format)
  3337.         if from_coords:
  3338.             args = args + ('-from',) + tuple(from_coords)
  3339.         self.tk.call(args)
  3340.  
  3341. class BitmapImage(Image):
  3342.     """Widget which can display a bitmap."""
  3343.     def __init__(self, name=None, cnf={}, master=None, **kw):
  3344.         """Create a bitmap with NAME.
  3345.  
  3346.         Valid resource names: background, data, file, foreground, maskdata, maskfile."""
  3347.         Image.__init__(self, 'bitmap', name, cnf, master, **kw)
  3348.  
  3349. def image_names(): return _default_root.tk.call('image', 'names')
  3350. def image_types(): return _default_root.tk.call('image', 'types')
  3351.  
  3352.  
  3353. class Spinbox(Widget):
  3354.     """spinbox widget."""
  3355.     def __init__(self, master=None, cnf={}, **kw):
  3356.         """Construct a spinbox widget with the parent MASTER.
  3357.  
  3358.         STANDARD OPTIONS
  3359.  
  3360.             activebackground, background, borderwidth,
  3361.             cursor, exportselection, font, foreground,
  3362.             highlightbackground, highlightcolor,
  3363.             highlightthickness, insertbackground,
  3364.             insertborderwidth, insertofftime,
  3365.             insertontime, insertwidth, justify, relief,
  3366.             repeatdelay, repeatinterval,
  3367.             selectbackground, selectborderwidth
  3368.             selectforeground, takefocus, textvariable
  3369.             xscrollcommand.
  3370.  
  3371.         WIDGET-SPECIFIC OPTIONS
  3372.  
  3373.             buttonbackground, buttoncursor,
  3374.             buttondownrelief, buttonuprelief,
  3375.             command, disabledbackground,
  3376.             disabledforeground, format, from,
  3377.             invalidcommand, increment,
  3378.             readonlybackground, state, to,
  3379.             validate, validatecommand values,
  3380.             width, wrap,
  3381.         """
  3382.         Widget.__init__(self, master, 'spinbox', cnf, kw)
  3383.  
  3384.     def bbox(self, index):
  3385.         """Return a tuple of X1,Y1,X2,Y2 coordinates for a
  3386.         rectangle which encloses the character given by index.
  3387.  
  3388.         The first two elements of the list give the x and y
  3389.         coordinates of the upper-left corner of the screen
  3390.         area covered by the character (in pixels relative
  3391.         to the widget) and the last two elements give the
  3392.         width and height of the character, in pixels. The
  3393.         bounding box may refer to a region outside the
  3394.         visible area of the window.
  3395.         """
  3396.         return self.tk.call(self._w, 'bbox', index)
  3397.  
  3398.     def delete(self, first, last=None):
  3399.         """Delete one or more elements of the spinbox.
  3400.  
  3401.         First is the index of the first character to delete,
  3402.         and last is the index of the character just after
  3403.         the last one to delete. If last isn't specified it
  3404.         defaults to first+1, i.e. a single character is
  3405.         deleted.  This command returns an empty string.
  3406.         """
  3407.         return self.tk.call(self._w, 'delete', first, last)
  3408.  
  3409.     def get(self):
  3410.         """Returns the spinbox's string"""
  3411.         return self.tk.call(self._w, 'get')
  3412.  
  3413.     def icursor(self, index):
  3414.         """Alter the position of the insertion cursor.
  3415.  
  3416.         The insertion cursor will be displayed just before
  3417.         the character given by index. Returns an empty string
  3418.         """
  3419.         return self.tk.call(self._w, 'icursor', index)
  3420.  
  3421.     def identify(self, x, y):
  3422.         """Returns the name of the widget at position x, y
  3423.  
  3424.         Return value is one of: none, buttondown, buttonup, entry
  3425.         """
  3426.         return self.tk.call(self._w, 'identify', x, y)
  3427.  
  3428.     def index(self, index):
  3429.         """Returns the numerical index corresponding to index
  3430.         """
  3431.         return self.tk.call(self._w, 'index', index)
  3432.  
  3433.     def insert(self, index, s):
  3434.         """Insert string s at index
  3435.  
  3436.          Returns an empty string.
  3437.         """
  3438.         return self.tk.call(self._w, 'insert', index, s)
  3439.  
  3440.     def invoke(self, element):
  3441.         """Causes the specified element to be invoked
  3442.  
  3443.         The element could be buttondown or buttonup
  3444.         triggering the action associated with it.
  3445.         """
  3446.         return self.tk.call(self._w, 'invoke', element)
  3447.  
  3448.     def scan(self, *args):
  3449.         """Internal function."""
  3450.         return self._getints(
  3451.             self.tk.call((self._w, 'scan') + args)) or ()
  3452.  
  3453.     def scan_mark(self, x):
  3454.         """Records x and the current view in the spinbox window;
  3455.  
  3456.         used in conjunction with later scan dragto commands.
  3457.         Typically this command is associated with a mouse button
  3458.         press in the widget. It returns an empty string.
  3459.         """
  3460.         return self.scan("mark", x)
  3461.  
  3462.     def scan_dragto(self, x):
  3463.         """Compute the difference between the given x argument
  3464.         and the x argument to the last scan mark command
  3465.  
  3466.         It then adjusts the view left or right by 10 times the
  3467.         difference in x-coordinates. This command is typically
  3468.         associated with mouse motion events in the widget, to
  3469.         produce the effect of dragging the spinbox at high speed
  3470.         through the window. The return value is an empty string.
  3471.         """
  3472.         return self.scan("dragto", x)
  3473.  
  3474.     def selection(self, *args):
  3475.         """Internal function."""
  3476.         return self._getints(
  3477.             self.tk.call((self._w, 'selection') + args)) or ()
  3478.  
  3479.     def selection_adjust(self, index):
  3480.         """Locate the end of the selection nearest to the character
  3481.         given by index,
  3482.  
  3483.         Then adjust that end of the selection to be at index
  3484.         (i.e including but not going beyond index). The other
  3485.         end of the selection is made the anchor point for future
  3486.         select to commands. If the selection isn't currently in
  3487.         the spinbox, then a new selection is created to include
  3488.         the characters between index and the most recent selection
  3489.         anchor point, inclusive. Returns an empty string.
  3490.         """
  3491.         return self.selection("adjust", index)
  3492.  
  3493.     def selection_clear(self):
  3494.         """Clear the selection
  3495.  
  3496.         If the selection isn't in this widget then the
  3497.         command has no effect. Returns an empty string.
  3498.         """
  3499.         return self.selection("clear")
  3500.  
  3501.     def selection_element(self, element=None):
  3502.         """Sets or gets the currently selected element.
  3503.  
  3504.         If a spinbutton element is specified, it will be
  3505.         displayed depressed
  3506.         """
  3507.         return self.selection("element", element)
  3508.  
  3509. ###########################################################################
  3510.  
  3511. class LabelFrame(Widget):
  3512.     """labelframe widget."""
  3513.     def __init__(self, master=None, cnf={}, **kw):
  3514.         """Construct a labelframe widget with the parent MASTER.
  3515.  
  3516.         STANDARD OPTIONS
  3517.  
  3518.             borderwidth, cursor, font, foreground,
  3519.             highlightbackground, highlightcolor,
  3520.             highlightthickness, padx, pady, relief,
  3521.             takefocus, text
  3522.  
  3523.         WIDGET-SPECIFIC OPTIONS
  3524.  
  3525.             background, class, colormap, container,
  3526.             height, labelanchor, labelwidget,
  3527.             visual, width
  3528.         """
  3529.         Widget.__init__(self, master, 'labelframe', cnf, kw)
  3530.  
  3531. ########################################################################
  3532.  
  3533. class PanedWindow(Widget):
  3534.     """panedwindow widget."""
  3535.     def __init__(self, master=None, cnf={}, **kw):
  3536.         """Construct a panedwindow widget with the parent MASTER.
  3537.  
  3538.         STANDARD OPTIONS
  3539.  
  3540.             background, borderwidth, cursor, height,
  3541.             orient, relief, width
  3542.  
  3543.         WIDGET-SPECIFIC OPTIONS
  3544.  
  3545.             handlepad, handlesize, opaqueresize,
  3546.             sashcursor, sashpad, sashrelief,
  3547.             sashwidth, showhandle,
  3548.         """
  3549.         Widget.__init__(self, master, 'panedwindow', cnf, kw)
  3550.  
  3551.     def add(self, child, **kw):
  3552.         """Add a child widget to the panedwindow in a new pane.
  3553.  
  3554.         The child argument is the name of the child widget
  3555.         followed by pairs of arguments that specify how to
  3556.         manage the windows. Options may have any of the values
  3557.         accepted by the configure subcommand.
  3558.         """
  3559.         self.tk.call((self._w, 'add', child) + self._options(kw))
  3560.  
  3561.     def remove(self, child):
  3562.         """Remove the pane containing child from the panedwindow
  3563.  
  3564.         All geometry management options for child will be forgotten.
  3565.         """
  3566.         self.tk.call(self._w, 'forget', child)
  3567.     forget=remove
  3568.  
  3569.     def identify(self, x, y):
  3570.         """Identify the panedwindow component at point x, y
  3571.  
  3572.         If the point is over a sash or a sash handle, the result
  3573.         is a two element list containing the index of the sash or
  3574.         handle, and a word indicating whether it is over a sash
  3575.         or a handle, such as {0 sash} or {2 handle}. If the point
  3576.         is over any other part of the panedwindow, the result is
  3577.         an empty list.
  3578.         """
  3579.         return self.tk.call(self._w, 'identify', x, y)
  3580.  
  3581.     def proxy(self, *args):
  3582.         """Internal function."""
  3583.         return self._getints(
  3584.             self.tk.call((self._w, 'proxy') + args)) or ()
  3585.  
  3586.     def proxy_coord(self):
  3587.         """Return the x and y pair of the most recent proxy location
  3588.         """
  3589.         return self.proxy("coord")
  3590.  
  3591.     def proxy_forget(self):
  3592.         """Remove the proxy from the display.
  3593.         """
  3594.         return self.proxy("forget")
  3595.  
  3596.     def proxy_place(self, x, y):
  3597.         """Place the proxy at the given x and y coordinates.
  3598.         """
  3599.         return self.proxy("place", x, y)
  3600.  
  3601.     def sash(self, *args):
  3602.         """Internal function."""
  3603.         return self._getints(
  3604.             self.tk.call((self._w, 'sash') + args)) or ()
  3605.  
  3606.     def sash_coord(self, index):
  3607.         """Return the current x and y pair for the sash given by index.
  3608.  
  3609.         Index must be an integer between 0 and 1 less than the
  3610.         number of panes in the panedwindow. The coordinates given are
  3611.         those of the top left corner of the region containing the sash.
  3612.         pathName sash dragto index x y This command computes the
  3613.         difference between the given coordinates and the coordinates
  3614.         given to the last sash coord command for the given sash. It then
  3615.         moves that sash the computed difference. The return value is the
  3616.         empty string.
  3617.         """
  3618.         return self.sash("coord", index)
  3619.  
  3620.     def sash_mark(self, index):
  3621.         """Records x and y for the sash given by index;
  3622.  
  3623.         Used in conjunction with later dragto commands to move the sash.
  3624.         """
  3625.         return self.sash("mark", index)
  3626.  
  3627.     def sash_place(self, index, x, y):
  3628.         """Place the sash given by index at the given coordinates
  3629.         """
  3630.         return self.sash("place", index, x, y)
  3631.  
  3632.     def panecget(self, child, option):
  3633.         """Query a management option for window.
  3634.  
  3635.         Option may be any value allowed by the paneconfigure subcommand
  3636.         """
  3637.         return self.tk.call(
  3638.             (self._w, 'panecget') + (child, '-'+option))
  3639.  
  3640.     def paneconfigure(self, tagOrId, cnf=None, **kw):
  3641.         """Query or modify the management options for window.
  3642.  
  3643.         If no option is specified, returns a list describing all
  3644.         of the available options for pathName.  If option is
  3645.         specified with no value, then the command returns a list
  3646.         describing the one named option (this list will be identical
  3647.         to the corresponding sublist of the value returned if no
  3648.         option is specified). If one or more option-value pairs are
  3649.         specified, then the command modifies the given widget
  3650.         option(s) to have the given value(s); in this case the
  3651.         command returns an empty string. The following options
  3652.         are supported:
  3653.  
  3654.         after window
  3655.             Insert the window after the window specified. window
  3656.             should be the name of a window already managed by pathName.
  3657.         before window
  3658.             Insert the window before the window specified. window
  3659.             should be the name of a window already managed by pathName.
  3660.         height size
  3661.             Specify a height for the window. The height will be the
  3662.             outer dimension of the window including its border, if
  3663.             any. If size is an empty string, or if -height is not
  3664.             specified, then the height requested internally by the
  3665.             window will be used initially; the height may later be
  3666.             adjusted by the movement of sashes in the panedwindow.
  3667.             Size may be any value accepted by Tk_GetPixels.
  3668.         minsize n
  3669.             Specifies that the size of the window cannot be made
  3670.             less than n. This constraint only affects the size of
  3671.             the widget in the paned dimension -- the x dimension
  3672.             for horizontal panedwindows, the y dimension for
  3673.             vertical panedwindows. May be any value accepted by
  3674.             Tk_GetPixels.
  3675.         padx n
  3676.             Specifies a non-negative value indicating how much
  3677.             extra space to leave on each side of the window in
  3678.             the X-direction. The value may have any of the forms
  3679.             accepted by Tk_GetPixels.
  3680.         pady n
  3681.             Specifies a non-negative value indicating how much
  3682.             extra space to leave on each side of the window in
  3683.             the Y-direction. The value may have any of the forms
  3684.             accepted by Tk_GetPixels.
  3685.         sticky style
  3686.             If a window's pane is larger than the requested
  3687.             dimensions of the window, this option may be used
  3688.             to position (or stretch) the window within its pane.
  3689.             Style is a string that contains zero or more of the
  3690.             characters n, s, e or w. The string can optionally
  3691.             contains spaces or commas, but they are ignored. Each
  3692.             letter refers to a side (north, south, east, or west)
  3693.             that the window will "stick" to. If both n and s
  3694.             (or e and w) are specified, the window will be
  3695.             stretched to fill the entire height (or width) of
  3696.             its cavity.
  3697.         width size
  3698.             Specify a width for the window. The width will be
  3699.             the outer dimension of the window including its
  3700.             border, if any. If size is an empty string, or
  3701.             if -width is not specified, then the width requested
  3702.             internally by the window will be used initially; the
  3703.             width may later be adjusted by the movement of sashes
  3704.             in the panedwindow. Size may be any value accepted by
  3705.             Tk_GetPixels.
  3706.  
  3707.         """
  3708.         if cnf is None and not kw:
  3709.             cnf = {}
  3710.             for x in self.tk.split(
  3711.                 self.tk.call(self._w,
  3712.                          'paneconfigure', tagOrId)):
  3713.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  3714.             return cnf
  3715.         if type(cnf) == StringType and not kw:
  3716.             x = self.tk.split(self.tk.call(
  3717.                 self._w, 'paneconfigure', tagOrId, '-'+cnf))
  3718.             return (x[0][1:],) + x[1:]
  3719.         self.tk.call((self._w, 'paneconfigure', tagOrId) +
  3720.                  self._options(cnf, kw))
  3721.     paneconfig = paneconfigure
  3722.  
  3723.     def panes(self):
  3724.         """Returns an ordered list of the child panes."""
  3725.         return self.tk.call(self._w, 'panes')
  3726.  
  3727. ######################################################################
  3728. # Extensions:
  3729.  
  3730. class Studbutton(Button):
  3731.     def __init__(self, master=None, cnf={}, **kw):
  3732.         Widget.__init__(self, master, 'studbutton', cnf, kw)
  3733.         self.bind('<Any-Enter>',       self.tkButtonEnter)
  3734.         self.bind('<Any-Leave>',       self.tkButtonLeave)
  3735.         self.bind('<1>',               self.tkButtonDown)
  3736.         self.bind('<ButtonRelease-1>', self.tkButtonUp)
  3737.  
  3738. class Tributton(Button):
  3739.     def __init__(self, master=None, cnf={}, **kw):
  3740.         Widget.__init__(self, master, 'tributton', cnf, kw)
  3741.         self.bind('<Any-Enter>',       self.tkButtonEnter)
  3742.         self.bind('<Any-Leave>',       self.tkButtonLeave)
  3743.         self.bind('<1>',               self.tkButtonDown)
  3744.         self.bind('<ButtonRelease-1>', self.tkButtonUp)
  3745.         self['fg']               = self['bg']
  3746.         self['activebackground'] = self['bg']
  3747.  
  3748. ######################################################################
  3749. # Test:
  3750.  
  3751. def _test():
  3752.     root = Tk()
  3753.     text = "This is Tcl/Tk version %s" % TclVersion
  3754.     if TclVersion >= 8.1:
  3755.         try:
  3756.             text = text + unicode("\nThis should be a cedilla: \347",
  3757.                                   "iso-8859-1")
  3758.         except NameError:
  3759.             pass # no unicode support
  3760.     label = Label(root, text=text)
  3761.     label.pack()
  3762.     test = Button(root, text="Click me!",
  3763.               command=lambda root=root: root.test.configure(
  3764.                   text="[%s]" % root.test['text']))
  3765.     test.pack()
  3766.     root.test = test
  3767.     quit = Button(root, text="QUIT", command=root.destroy)
  3768.     quit.pack()
  3769.     # The following three commands are needed so the window pops
  3770.     # up on top on Windows...
  3771.     root.iconify()
  3772.     root.update()
  3773.     root.deiconify()
  3774.     root.mainloop()
  3775.  
  3776. if __name__ == '__main__':
  3777.     _test()
  3778.